Mohit Garg
Mohit Garg

Reputation: 355

C - pow function unexpected behavior

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!

Upvotes: 0

Views: 91

Answers (2)

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18825

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).

Upvotes: 0

Bryan Jarmain
Bryan Jarmain

Reputation: 38

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).

Upvotes: 1

Related Questions