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

雨燕双飞 提交于 2020-04-17 22:40:19

问题


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



来源:https://stackoverflow.com/questions/60572057/why-do-the-square-of-input-decreases-by-one-when-using-pow-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!