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