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
				
        
 
            
        基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				