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循环计算数字
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
