-
How many digits?
Hi all!
I need to find a way of calculating the number of digits in an integer, here's a glimpse of what I've got so far:
Code:
if ( ( userdigit / 1 ) < 1 )
{
cout << "1 digit integer!";
}
else if ( ( userdigit / 10 ) < 1 )
{
cout << "2 digit integer!";
}
else if ( ( userdigit / 100 ) < 1 )
{
cout << "3 digit integer!";
}
else if ( ( userdigit / 1000 ) < 1 )
{
cout << "4 digit integer!";
}
else if ( ( userdigit / 10000 ) < 1 )
{
cout << "5 digit integer!";
}
... And variants of, none of which have been any success!
Does anybody have a good way of doing this?
-
Careful use of log10 from <cmath> could yield what you desire. Alternatively, you could loop with a similiar idea as to what you showed in your example code.
-
I urge you to take a good hard look at that first line. Really think about it for a bit. What is the result of dividing by one going to be?
You certainly can do it somewhat along the lines of what you have, but you definitely haven't quite got it right.
-
OMG!!! I'm such a thicko!!!
:-)
-
It's merely a case of having an idea, and then coding it up simply by following a pattern, and not stopping to realise that it's a little off.
The first one is in fact easy, you know exactly what to write, it's when the value is less than ten. From there you can actually easily derive a recursive solution if you wanted to, since if it was not less than 10 then you can divide it by ten and test again, knowing that if it's less than ten this time then there were two digits, and so on.