Sep 5, 2012 at 3:35am UTC
It worked! But if I put in an eleven digit number it still says it is ten digits.
// How many digits
#include <iostream>
using namespace std;
int main ()
{int integer;
cout << "Enter an integer." ;
cin >> integer;
cout << "The number of digits the integer has is ";
if (integer < 0){
integer = integer * -1;
cout << "negative. " << endl;
}
else if (integer <= 9){
cout << "one digit. " << endl;
}
else if (integer <= 99){
cout << "two digits. " << endl;
}
else if (integer <= 999){
cout << "three digits. " << endl;
}
else if (integer <= 9999){
cout << "four digits. " << endl;
}
else if (integer <= 99999){
cout << "five digits. " << endl;
}
else if (integer <= 999999){
cout << "six digits. " << endl;
}
else if (integer <= 9999999){
cout << "seven digits. " << endl;
}
else if (integer <= 99999999){
cout << "eight digits. " << endl;
}
else if (integer <= 999999999){
cout << "nine digits. " << endl;
}
else if (integer <= 9999999999LLU){
cout << "ten digits. " << endl;
}
else if (integer <= 99999999999LLU){
cout << "eleven digits. " << endl;
}
system ("pause");
return 0;
}
Sep 5, 2012 at 3:40am UTC
Depends on what 10 digit number you're using because if it's greater than the max integer the number will "rollover" and become negative.
Sep 5, 2012 at 3:41am UTC
Anyways your code isn't really the "correct" way to check the number of digits in a number as it doesn't handle a lot of cases. There is an algorithm for determining the number of digits but if you're just starting off learning programming then this is fine as long as you don't try anything "fancy".