问题描述
我最近正在制作一个程序,需要检查用户输入的数字中的位数.结果我做了以下代码:
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循环计算数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!