如何计算 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";