为什么在 C++ 中 pow(10,5) = 9,999 [英] Why pow(10,5) = 9,999 in C++

查看:25
本文介绍了为什么在 C++ 中 pow(10,5) = 9,999的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我写了一段代码:

const int sections = 10;

for(int t= 0; t < 5; t++){
   int i = pow(sections, 5- t -1);  
   cout << i << endl;
}

结果是错误的:

9999
1000
99
10
1

如果我只使用这个代码:

If i using just this code:

for(int t = 0; t < 5; t++){
    cout << pow(sections,5-t-1) << endl; 
}

问题不再发生:

10000
1000
100
10
1

有人给我解释一下吗?非常感谢!

Does anyone give me an explaination? thanks you very much!

推荐答案

由于浮点值的表示,pow(10.0, 5) 可能是 9999.9999999 或类似的东西.当您将其分配给被截断的整数时.

Due to the representation of floating point values pow(10.0, 5) could be 9999.9999999 or something like this. When you assign that to an integer that got truncated.

如果 cout << 看起来输出是四舍五入的,但我现在没有任何支持文件来证实这一点.

In case of cout << pow(10.0, 5); it looks like the output is rounded, but I don't have any supporting document right now confirming that.

编辑 2:由 BoBTFish 和 这个问题 证实了当 pow(10.0, 5) 直接在 cout 中使用时,会被四舍五入.

EDIT 2: The comment made by BoBTFish and this question confirms that when pow(10.0, 5) is used directly in cout that is getting rounded.

这篇关于为什么在 C++ 中 pow(10,5) = 9,999的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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