如何计算c ++中的整数位数?

-3 c++ visual-studio-2010

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

我这样做了

`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;
}
Run Code Online (Sandbox Code Playgroud)

如何设置最多6位数的条件,为什么"a"输出为0?

Jon*_*ely 5

你运行循环,直到a==0循环后它将是0.

获取副本a并修改副本或打印副本.不要指望修改a然后仍然具有原始值.

您不需要最多6位数的条件.有人告诉你,你可能假设不超过6位数.这并不意味着您不能编写超过6的解决方案,或者您必须强制执行不超过6位数的解决方案.