While writing a function which will perform some operation with each number in a range I ran into some problems with floating point inaccuracies. The problem can be seen in the code below:
#include <iostream>
using namespace std;
int main()
{
double start = .99999, end = 1.00001, inc = .000001;
int steps = (end - start) / inc;
for(int i = 0; i <= steps; ++i)
{
cout << (start + (inc * i)) << endl;
}
}
The problem is that the numbers the above program outputs look like this:
0.99999
0.999991
0.999992
0.999993
0.999994
0.999995
0.999996
0.999997
0.999998
0.999999
1
1
1
1
1
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001
They only appear to be correct up to the first 1. What is the proper way to solve this problem?
Your sample output only looks wrong because of how
ostreamrounds by default. You can setprecisionto get some other output.Here’s what I get now: