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

时间:2016-03-18 21:49:44

标签: 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;
}

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

3 个答案:

答案 0 :(得分:5)

你运行循环直到a==0,所以当然循环后它将为0。

获取a的副本,然后修改副本或打印副本。不要期望修改a,然后仍然保留原始值。

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

答案 1 :(得分:2)

一些变化......

#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;
}

答案 2 :(得分: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";