0

This is a program to find number of digits.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
    int i = 0, n;
    printf("Enter number: ");
    scanf("%d", &n);
    while ((n / pow(10, i)) != 0) {
        i++;
    }
    printf("%d", i);
}

This program gives 309 as the output (value of i) on any input. However, if I store the value of pow(10, i) in another variable and put it in while loop, I get the correct output. Please help!

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Mohit Garg
  • 355
  • 4
  • 16

2 Answers2

1

C++ uses the most precise type (when types are mixed) when doing a calculation or evaluation, and here you are effectively mixing a double with an int. You are dividing a user input number by a very large exponential number.

This in theory will never be zero, no matter how big the divisor gets. So, the theoretical result should be infinite. However, due to the limits of a double (which is returned by pow), it will still eventually approximate zero.

If you store the return of pow in an integer, you will no longer be mixing types and will effectively be working out the number of digits or what the approximate log base 10 is (any integer divide by a larger integer will equal zero).

0

Change:

while( ( n / pow(10,i) )!=0 ){

To:

while( ( n / pow(10,i) ) >= 1 ){

pow returns double and therefore the full result is double and the fractional part will be always non-zero until running out of exponent possible values which is 309 (translated to decimal, binary is 1024).

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
  • Thanks for your reply! , but if i write this: z = n / pow(10,i) ; printf("%lf", z); , the output is 0.000000 . Could you please explain that ? – Mohit Garg Feb 14 '16 at 17:01
  • 1
    @MohitGarg: how do you define `z` in `z = n / pow(10,i) ; printf("%lf", z);`? – chqrlie Feb 14 '16 at 17:12
  • @MohitGarg : by default `printf()` outputs to 6 decimal places, but a `double` is good for 15 significant figures. Use "`"%.15lf"` or better a debugger to see the full value of `z`. – Clifford Feb 14 '16 at 17:22
  • @Clifford Using `"%.15f"` shows no significance for values like `1.0e-20` and is verbose for `1.0e+20`. Recommend `"%.16e"` (e vs f) to see 17 significant digits. [Ref](http://stackoverflow.com/q/16839658/2410359) – chux - Reinstate Monica Feb 14 '16 at 23:04
  • @chux : Good point; *significant figures != decimal places*. As I said though, better observed in a debugger than user defined formatted I/O - because you can get it as wrong as I just did! – Clifford Feb 15 '16 at 11:06