为什么使用pow函数时输入的平方减少1? [英] Why do the square of input decreases by one when using pow function?

查看:322
本文介绍了为什么使用pow函数时输入的平方减少1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的C程序,它接受用户输入的数字并得出平方.

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;
}

问题是,每当我输入5,25,26等作为输入时,输出为24,624,675,即它减少1并且并非所有数字都这样.我正在使用CodeBlocks IDE.我想出了一个解决此问题的方法,但我想知道幕后正在发生什么,这是导致此错误的原因.

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.

推荐答案

来自这篇文章,苏拉夫告诉我们:

From this post, Sourav tells us:

pow()接受双精度参数并返回双精度值.

pow() takes double arguments and returns a double.

如果将返回值存储在int中并打印出来,则可能无法获得所需的结果.

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

关于 为什么 的解释,pow()返回的值比您期望的少1,请参见

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

pow()使用双数.这些表示形式为s * 2^e的数字​​,其中s是53位整数.因此,double可以存储2^53以下的所有整数,但只能存储2^53以上的一些整数.特别是,它只能表示偶数> 2^53,因为对于e > 0,该值始终是2的倍数.

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.

这篇关于为什么使用pow函数时输入的平方减少1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆