C:我买了POW(10,2)和POW(10,J),J = 2不同的结果; [英] C: i got different results with pow(10,2) and pow(10,j), j=2;

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

问题描述

这一个打印100:

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

而这一次打印99:

and this one prints 99:

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

为什么?

推荐答案

这是怎么回事的是,你有一个C实现,其标准库有一个非常低质量的实施 POW 这是返回结果不精确,即使确切的结果在类型重新presentable(双击)。到 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.

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

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