Counting digits using while loop(使用while循环计算数字)
问题描述
我最近正在制作一个程序,需要检查用户输入的数字中的位数.结果我做了以下代码:
I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:
int x;
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
count++;
x = x/10;
}
据我所知(即使我的经验有限),它看起来很粗糙,而且相当不雅.
From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.
有没有人知道如何改进此代码(同时不使用内置的 C++ 函数)?
Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?
推荐答案
在您的特定示例中,您可以将数字作为字符串读取并计算字符数.
In your particular example you could read the number as a string and count the number of characters.
但对于一般情况,您可以按照自己的方式进行操作,也可以使用以 10 为底的对数.
But for the general case, you can do it your way or you can use a base-10 logarithm.
这里是对数示例:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double n;
cout << "Enter a number: ";
cin >> n;
cout << "Log 10 is " << log10(n) << endl;
cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
return 0;
}
这篇关于使用while循环计算数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用while循环计算数字


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01