为什么POW(N,2)返回24当n = 5,用我的编译器和操作系统? [英] Why does pow(n,2) return 24 when n=5, with my compiler and OS?
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n,i,ele;
n=5;
ele=pow(n,2);
printf("%d",ele);
return 0;
}
输出为 24
。
我在code :: Blocks的使用GNU / GCC。
I'm using GNU/GCC in Code::Blocks.
这是怎么回事?
我知道 POW
函数返回一个双击
,但 25
适合int类型那么,为什么这个code打印一个 24
,而不是 25
?如果 N = 4; N = 6; N = 3; N = 2;
的code的作品,但与五它没有
I know the pow
function returns a double
,but 25
fits an int type so why does this code print a 24
instead of a 25
? If n=4; n=6; n=3; n=2;
the code works, but with the five it doesn't.
推荐答案
下面是可能发生在这里。您应该能够通过查看你的编译器的实施 POW
函数来证实这一点:
Here is what may be happening here. You should be able to confirm this by looking at your compiler's implementation of the pow
function:
假设你有正确的#包括的,(所有的previous答案和传播评论是否正确 - 不采取的#include
文件是理所当然的),原型为标准 POW
函数是这样的:
Assuming you have the correct #include's, (all the previous answers and comments about this are correct -- don't take the #include
files for granted), the prototype for the standard pow
function is this:
双战俘(双,双);
和你打电话 POW
是这样的:
POW(5,2);
的 POW
函数经过一个算法(可能使用对数),因此使用浮点功能和价值来计算功率值。
The pow
function goes through an algorithm (probably using logarithms), thus uses floating point functions and values to compute the power value.
的 POW
功能不经过幼稚乘XA共有n次的价值,因为它也计算 POW
使用分数指数,你可以不计算分数幂的方式。
The pow
function does not go through a naive "multiply the value of x a total of n times", since it has to also compute pow
using fractional exponents, and you can't compute fractional powers that way.
所以更可能的, POW
的使用参数5和2的计算结果是轻微的舍入误差。当你分配到 INT
,你截断小数值,从而产生24。
So more than likely, the computation of pow
using the parameters 5 and 2 resulted in a slight rounding error. When you assigned to an int
, you truncated the fractional value, thus yielding 24.
如果您使用的是整数,你还不如写自己的intpow或类似的功能,简单地乘以值的次数必要数量。这样做的好处是:
If you are using integers, you might as well write your own "intpow" or similar function that simply multiplies the value the requisite number of times. The benefits of this are:
-
您将无法进入情况下,你可以使用
POW
获得微妙的舍入误差。
您 intpow
功能将超过到 POW
可能运行比同等调用更快。
Your intpow
function will more than likely run faster than an equivalent call to pow
.
这篇关于为什么POW(N,2)返回24当n = 5,用我的编译器和操作系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!