Just curious because it would make printing out an matrix much easier.
Thanks.
This is a discussion on is there a function that counts the digits of an int within the C Programming forums, part of the General Programming Boards category; Just curious because it would make printing out an matrix much easier. Thanks....
Just curious because it would make printing out an matrix much easier.
Thanks.
Code:#include <math.h> ... (int)log10( n ) + 1;
Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah
You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie
The obvious way is to sprintf() it to a temp buffer and then use strlen
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
is the (int) necessary in front of the log(n)?
yes it should be... I think you could have problems using log10 because of rounding errors.
>Just curious because it would make printing out an matrix much easier.
There is also this macro I found on another list.This performs (an approximation of) the logarithmic calculation at compile time.Code:#include <stdio.h> #include <limits.h> #define DECIMALS(itype) \ (sizeof(itype) * (CHAR_BIT * 12655UL) / 42039 \ + ((itype)-1 < 0) + 1) int main(void) { int matrix[][5] = { { INT_MIN, INT_MIN + 1, INT_MIN + 2, -1, 0 }, { 0, 1, INT_MAX - 2, INT_MAX - 1, INT_MAX }, }; size_t i,j; for(i = 0; i < sizeof matrix / sizeof *matrix; ++i) { for(j = 0; j < sizeof *matrix / sizeof **matrix; ++j) { printf("%*d ", DECIMALS(int), matrix[i][j]); } putchar('\n'); } return 0; } /* my output -2147483648 -2147483647 -2147483646 -1 0 0 1 2147483645 2147483646 2147483647 */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Speaking of macros...
Quzah.Code:#define ULEN32(x) ( \ (x)<10?1: \ (x)<100?2: \ (x)<1000?3: \ (x)<10000?4: \ (x)<100000?5: \ (x)<1000000?6: \ (x)<10000000?7: \ (x)<100000000?8: \ (x)<1000000000?9: 10 )
Hope is the first step on the road to disappointment.
Many suggestions so far. Oh well, here's another:
(Only works for positive integers, and 0 comes out as 0 digits though, you could use a special case if this is unwanted)Code:int GetNrOfDigits(int Number) { int Digits = 0; while(Number > 0) { Digits++; Number /= 10; } return Digits; }
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
Code:int GetNrOfDigits(int Number) { int Digits = 0; do { Digits++; Number /= 10; } while(Number > 0); return Digits; }