i need to fnid out how many digits make up a number.
i thought about using modulus first but figured that wouldnt work.
have i overlooked a built-in function ??
i need to fnid out how many digits make up a number.
i thought about using modulus first but figured that wouldnt work.
have i overlooked a built-in function ??
"with a gun barrel between your teeth, you speak only in vowels."
- tyler durden
the fastest brute force way to do this is actually a long string of conditionals, but unless there's some urgent need for speed, use a loop and divide by 10, something like
while (number > 0)
{
digits++;
number = number / 10;
}
hello, internet!
what if the number is 00000. there are 5 digits.
00000 = 0 and wont be divided by 10.
"with a gun barrel between your teeth, you speak only in vowels."
- tyler durden
no it doesnt, 00000 has 0 digits just like 0.Originally posted by glowstick
what if the number is 00000. there are 5 digits.
hello, internet!
00000 has 5 digits.
"with a gun barrel between your teeth, you speak only in vowels."
- tyler durden
Is it user input or data within the program?
If it's user input, capture it as a string, validate that digits have been entered, then use something like strlen to get the size of the string (or count array elements, whatever). Then use atoi or similar to turn it into a number if that's what you need.
Demonographic rhinology is not the only possible outcome, but why take the chance
I'm lazy.Code:int numlen( int num ) { char buf[BUFSIZ]={0}; sprintf(buf, "%d", num ); return strlen( buf ); }
Quzah.
Hope is the first step on the road to disappointment.
that'll work. thanks.Originally posted by Azuth
Is it user input or data within the program?
If it's user input, capture it as a string, validate that digits have been entered, then use something like strlen to get the size of the string (or count array elements, whatever). Then use atoi or similar to turn it into a number if that's what you need.
"with a gun barrel between your teeth, you speak only in vowels."
- tyler durden
Or:
#include <math.h>
.
.
int num_of_digits;
num_of_digits = (int) log10((double) num) + 1;
If you're wanting to count the leading zero's, I can't see any amount of maths giving you the answer.... the only way, as already posted, is using a string (char array).
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
thats what i have decided to do and it works lie a charm. in fact i just left it as a char array and printed as a string.Originally posted by Hammer
If you're wanting to count the leading zero's, I can't see any amount of maths giving you the answer.... the only way, as already posted, is using a string (char array).
"with a gun barrel between your teeth, you speak only in vowels."
- tyler durden