Why pow(10,5) = 9,999 in C++(为什么在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 C++ 中 pow(10,5) = 9,999


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01