如何在 c++ 中计算整数位数

How to count number of integer digits in c++?

本文关键字:整数 计算 c++      更新时间:2023-10-16

我的任务是编写一个程序来计算一个数字包含多少位数字。您可以假设该数字不超过六位数字。

我做到了

`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";