简体   繁体   中英

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

My task is to write a program that calculates how many digits a number contains. You may assume that number has no more than six digits.

I did this

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

How can I put condition that there are max 6 digits, and why is "a" outputting as a 0?

You run the loop until a==0 so of course it will be 0 after the loop.

Take a copy of a and either modify the copy, or print out the copy. Don't expect to modify a and then still have the original value.

You don't need a condition that it has max 6 digits. You were told you may assume no more than 6 digits. That doesn't mean you can't write a solution that works for more than 6, or that you must enforce no more than 6 digits.

A few changes...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM