pow 函数的奇怪行为 [英] Strange behaviour of the pow function

查看:30
本文介绍了pow 函数的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时运行以下几行代码:

While running the following lines of code:

int i,a;    

for(i=0;i<=4;i++)  
{    
    a=pow(10,i);    
    printf("%d	",a);    
}   

我很惊讶地看到输出,结果是1 10 99 1000 9999 而不是 1 10 100 1000 10000.

I was surprised to see the output, it comes out to be 1 10 99 1000 9999 instead of 1 10 100 1000 10000.

可能的原因是什么?

注意
如果您认为在上述for循环中,当i = 2时,浮点数不准确,则存储在变量a中的值为99.

Note
If you think it's a floating point inaccuracy that in the above for loop when i = 2, the values stored in variable a is 99.

但是如果你改写

a=pow(10,2);

现在 a 的值是 100.这怎么可能?

now the value of a comes out to be 100. How is that possible?

推荐答案

我什至不会拼写 c,但我可以告诉你为什么.

I can't even spell c, but I can tell you why.

您已将 a 设置为 int.pow() 生成一个浮点数,在某些情况下,它可能只是小于 100 或 10000(正如我们在这里看到的)的头发.

You have set a to be an int. pow() generates a floating point number, that in SOME cases may be just a hair less than 100 or 10000 (as we see here.)

然后将其填充到整数中,然后将其截断为整数.所以你失去了那个小数部分.哎呀.如果您确实需要一个整数结果,那么 round 可能是执行该操作的更好方法.

Then you stuff that into the integer, which TRUNCATES to an integer. So you lose that fractional part. Oops. If you really needed an integer result, round may be a better way to do that operation.

即使在那里也要小心,至于足够大的权力,错误实际上可能足够大,仍然会导致失败,给你一些你意想不到的东西.请记住,浮点数仅具有如此高的精度.

Be careful even there, as for large enough powers, the error may actually be large enough to still cause a failure, giving you something you don't expect. Remember that floating point numbers only carry so much precision.

这篇关于pow 函数的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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