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

查看:290
本文介绍了为什么在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

如果我只使用这个代码:

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

问题不再发生:

  10000 
1000
100
10
1
pre>

有没有人给我一个解释?非常感谢!

解决方案

由于浮点值的表示 pow 可能是9999.9999999或这样的东西。



编辑: cout<< pow(10.0,5); 它看起来像输出四舍五入,但我没有任何支持文档,现在确认。



EDIT 2:BoBTFish和此问题确认在 cout 中直接使用 pow(10.0,5)变圆。


Recently i write a block of code:

const int sections = 10;

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

And the result is wrong:

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; 
}

The problem doesn't occur anymore:

10000
1000
100
10
1

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

解决方案

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.

EDIT: 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.

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天全站免登陆