問題描述
我有一個在 32 位 Ubuntu 8.04 上使用 gcc 4.2.4 編譯的簡單 C++ 程序.它有一個 for
循環,其中 double
變量以特定步長從 0 遞增到 1.當步長為 0.1
時,行為正是我所期望的.但是當步長為'0.05'時,循環在0.95
后退出.誰能告訴我為什么會這樣?輸出遵循下面的源代碼.
I have a simple C++ program compiled using gcc 4.2.4 on 32-bit Ubuntu 8.04. It has a for
-loop in which a double
variable is incremented from zero to one with a certain step size. When the step size is 0.1
, the behavior is what I expected. But when the step size is '0.05', the loop exits after 0.95
. Can anyone tell me why this is happening? The output follows the source code below.
#include <iostream>
using namespace std;
int main()
{
double rangeMin = 0.0;
double rangeMax = 1.0;
double stepSize = 0.1;
for (double index = rangeMin; index <= rangeMax; index+= stepSize)
{
cout << index << endl;
}
cout << endl;
stepSize = 0.05;
for (double index = rangeMin; index <= rangeMax; index+= stepSize)
{
cout << index << endl;
}
return 0;
}
輸出
sarva@savija-dev:~/code/scratch$ ./a.out
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
sarva@savija-dev:~/code/scratch$
推薦答案
當使用浮點值時,并非每個值都可以精確表示,0.95+0.05 >1
因為 0.95
不能完全用 double
值表示.
When using floating point values not every value is exactly representable, 0.95+0.05 > 1
because 0.95
is not exactly representable by a double
value.
看看維基百科對浮點精度的看法.
See what Wikipedia has to say about floating point accuracy.
如果您查看 IEEE 浮點轉換器,您會看到0.95
在 64 位浮點數 (double
) 中的值是 0-01111111110-1110011001100110011001100110011001100110011000
輸入這個http://www.ajdesigner.com/fl_ieee_754_word/ieee_32_bit_word.php" rel="nofollow noreferrer">浮點計算器 你得到的值為
0.95000016
并添加 0.05
將帶您超越 1.0
標記.
If you look at the IEEE floating point converter you'll see that the value of 0.95
in 64 bit floating point (double
) is 0-01111111110-1110011001100110011001100110011001100110011001100110
by entering this in a floating point calculator you get the value is 0.95000016
and adding 0.05
to that takes you over the 1.0
mark.
這就是為什么你永遠不應該在循環中使用浮點數(或者更一般地說,將浮點計算的結果與精確值進行比較).
This is why you should never use floating points in loops (or more generally compare the result of floating point calculation to an exact value).
這篇關于C++ 中的 For 循環使用雙突破提前一步,未達到邊界值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!