如何在 c++ 中计算整数位数
How to count number of integer digits in c++?
我的任务是编写一个程序来计算一个数字包含多少位数字。您可以假设该数字不超过六位数字。
我做到了
`enter code here`
#include <iostream>
using namespace std;
int main () {
int a, counter=0;;
cout<<"Enter a number: ";
cin>>a;
while (a!=0) {
a=a/10;
counter++;
}
cout<<"The number "<<a<<" has "<<counter<<" digits."<<endl;
system ("PAUSE");
return 0;
}
我怎样才能设置最多有 6 位数字的条件,为什么"a"输出为 0?
你运行循环直到a==0
所以循环后当然会是 0。
获取a
的副本,然后修改副本或打印出副本。 不要期望修改a
然后仍然具有原始值。
您不需要最多包含 6 位数字的条件。您被告知您可以假设不超过 6 位数字。这并不意味着您不能编写适用于超过 6 位的解决方案,或者您必须强制使用 6 位数字。
一些变化...
#include <iostream>
using namespace std;
int main () {
int a, counter=0;;
cout<<"Enter a number: ";
cin>>a;
int workNumber = a;
while (workNumber != 0) {
workNumber = workNumber / 10;
counter++;
}
if(a == 0)
counter = 1; // zero has one digit, too
if(counter > 6)
cout << "The number has too many digits. This sophisticated program is limited to six digits, we are inconsolable.";
else
cout<<"The number "<<a<<" has "<<counter<<" digits."<<endl;
system ("PAUSE");
return 0;
}
int n;
cin >> n;
int digits = floor(log10(n)) + 1;
if (digits > 6) {
// do something
}
std::cout << "The number " << n << " has " << digits << " digits.n";
相关文章:
- 如何计算整数的十进制数字?
- 计算总和为 x 的所有整数子集(包括负数)
- 如何计算整数链中使用了多少次数字?
- 计算负基数的正非整数幂
- 通过在带有 C++ 的列表中添加连续元素来计算新的整数列表
- 我在c++中遇到了一个奇怪的错误,其中一个计算2个小整数加法的语句溢出到一个长值中
- 计算将整数n分解为4平方和的方法的数量
- 如何计算数组整数的总可能组合
- 当我们C++将两个数组的整数除以 时,如何获得浮点数计算;
- 计算 (64 位无符号整数) * (64 位无符号整数) 的商除以 2^64
- 为什么按位运算符在使用与整数中提供的位数相同的位数计算可能的最大范围时会产生错误
- 如何使用 C++ std 计算整数集合的前导零和尾随零
- 运算符"|"如何计算两个整数?
- 如何计算两个负整数 c++ 之间的总和
- 从文本文件中读取并使用 sizeof 结果计算整数的数量到 nan
- C 和 C++ 中的整数计算溢出
- 仅使用整数计算两条线的交点
- 一种在C++中执行基本 128 位整数计算的有效方法
- 算法C/C++:用n和d 32或64位整数计算(2^n)%d的最快方法
- 整数计算的二项式系数使用boost::math::binomial_coefficient,返回值为boost::mul