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循环计算数字


- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01