Search code examples
cpow

`pow(x, 15)` function in C giving wrong (large negative) result for values of x >= 5


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

main() 
{

    int x, y;

    printf("Enter a number ");
    scanf("%d", &x);

    y = pow(x,15);

    printf("This is your new number %d", y);
}

When I pass x as 2, 3 or 4 it gives the correct result, but when I pass in 5 or any number higher than 5, it gives -2147483648, which is obviously incorrect.

What is the problem here? Any thoughts?


Solution

  • In your environment, the int data type is not large enough to hold the value 515. The int type on your system is likely only 32-bit, and since it is a signed type, you have only 31 bits, so the largest positive integer that it can hold is (232 - 1).

    Since 515 > (232 - 1), the result that is stored in y overflows. Since pow returns double type, the behaviour of this overflowing conversion is undefined. As with all undefined behaviour, there is no guarantee about what will happen. Even running the same program twice in a row may produce different results.