我用 pow(10,2) 和 pow(10,j), j=2; 得到了不同的结果; [英] I got different results with pow(10,2) and pow(10,j), j=2;

查看:12
本文介绍了我用 pow(10,2) 和 pow(10,j), j=2; 得到了不同的结果;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个打印100:

int j=2;
int i= pow(10,2);  
printf("%d
", i);

这个打印 99:

int j=2;
int i= pow(10,j);  
printf("%d
", i);

为什么?

推荐答案

您有一个 C 实现,其标准库的 pow 实现质量非常低,返回的结果不准确即使确切的结果可以用类型 (double) 表示.对 pow(10,2) 的调用似乎产生了低于 100.0 的值,当四舍五入为整数时,产生 99.你看不到的原因当参数是常量时,编译器冒昧地对调用进行了优化,并在编译时将其替换为常量 100.

What's going on is that you have a C implementation whose standard library has a very low quality implementation of pow which is returning inexact results even when the exact result is representable in the type (double). The call to pow(10,2) seems to producing the value just below 100.0, which, when rounded to an integer, yields 99. The reason you don't see this when the arguments are constant is that the compiler took the liberty to optimize out the call alltogether and replace it with a constant 100 at compiletime.

如果您的意图是进行整数幂运算,请不要使用 pow 函数.写一个适当的整数幂函数,或者当指数已知时,直接写出乘法.

If your intent is to do integer powers, don't use the pow function. Write a proper integer power function, or when the exponent is known, just write out the multiplication directly.

这篇关于我用 pow(10,2) 和 pow(10,j), j=2; 得到了不同的结果;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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