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循环计算数字
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
