最近我写了一段代码:
const int sections = 10;
for(int t= 0; t < 5; t++){
int i = pow(sections, 5- t -1);
cout << i << endl;
}
Run Code Online (Sandbox Code Playgroud)
结果是错误的:
9999
1000
99
10
1
Run Code Online (Sandbox Code Playgroud)
如果我只使用这个代码:
for(int t = 0; t < 5; t++){
cout << pow(sections,5-t-1) << endl;
}
Run Code Online (Sandbox Code Playgroud)
问题不再发生:
10000
1000
100
10
1
Run Code Online (Sandbox Code Playgroud)
有没有人给我解释?非常感谢你!
tas*_*oor 12
由于浮点值的表示pow(10.0, 5)可能是9999.9999999或类似的东西.将其分配给已截断的整数时.
编辑:如果cout << pow(10.0, 5);它看起来像输出四舍五入,但我现在没有任何支持文件确认.
编辑2:BoBTFish发表的评论和这个问题证实了pow(10.0, 5)直接使用的时候是cout圆满的.