32ビットUbuntu8.04でgcc4.2.4を使用してコンパイルされた単純なC++プログラムがあります。変数がゼロから特定のステップサイズで1にインクリメントされるfor
ループがあります。double
ステップサイズがの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$