If a for loop "iterates" a double from 0.00 to 0.40, for example, even when writing <=
, the loop terminates when i=39
. When performing essentially the same thing using integers, the program acts normally.
#include <iostream>
using namespace std;
int main() {
for (double i = 0.00; i <= 0.40; i += 0.01) {
cout << i << " ";
}
return 0;
}
This returns 1 2 3
... 37 38 39
.
You can test this here: https://ideone.com/bP3ilk
What causes this behavior and is there an ideal way to fix this, as just writing i <= 0.41
seems like a hacky solution. Even more so if the 0.40 was a user entered value, adding a small quantity certainly be considered bad practice.
Sorry if the title and question are poorly phrases, I'm not sure how to word this.