我在 32 位 Ubuntu 8.04 上使用 gcc 4.2.4 编译了一个简单的 C++ 程序。它有一个 for
循环,其中一个 double
变量以一定的步长从零递增到 1。当步长为 0.1
时,行为符合我的预期。但是当步长为“0.05”时,循环在 0.95
后退出。谁能告诉我为什么会这样?输出遵循下面的源代码。
#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
值精确表示。
看看维基百科对 floating point accuracy 的看法。
如果您查看 IEEE floating point converter,您会看到 64 位 float (0.95
) 中 double
的值是 0-01111111110-1110011001100110011001100110011001100110011001100110
,通过在 floating point calculator 中输入它,您得到的值是 0.95000016
并且将 0.05
添加到 405 超过 5x7标记。
这就是为什么你永远不应该在循环中使用 float (或者更一般地说,将浮点计算的结果与一个精确值进行比较)。
关于c++ - C++中的for循环提前一步使用双重突破,未达到边界值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1286394/