Why do the square of input decreases by one when using pow function?

193 views Asked by At

Here is a simple C program, which accepts a number from the user and results it's square.

#include <stdio.h>
#include <math.h>
int main()
{
    int number;
    int result;
    printf("\nEnter the number\n");
    scanf("%d",&number);
    result=(pow(number,2));
    printf("\nThe result is %d\n",result);
    return 0;
}

The problem is, whenever i enter 5,25,26 etc as input, the output is 24,624,675 i.e. it decreases by 1 and this does not happen with all numbers. I am using CodeBlocks IDE. I figured out a fix for this problem but I want to know what is happening behind the scene, which is causing this error.

1

There are 1 answers

2
agillgilla On

From this post, Sourav tells us:

pow() takes double arguments and returns a double.

If you store the return value into an int and print that, you may not get the desired result.

As for an explanation on why pow() is returning 1 less that you expect, see this post. Specifically:

pow() works with double numbers. These represent numbers of the form s * 2^e where s is a 53 bit integer. Therefore double can store all integers below 2^53, but only some integers above 2^53. In particular, it can only represent even numbers > 2^53, since for e > 0 the value is always a multiple of 2.