问题
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:
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 forms * 2^e
wheres
is a 53 bit integer. Therefore double can store all integers below2^53
, but only some integers above2^53
. In particular, it can only represent even numbers> 2^53
, since fore > 0
the value is always a multiple of 2.
来源:https://stackoverflow.com/questions/60572057/why-do-the-square-of-input-decreases-by-one-when-using-pow-function