2

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.

Will Hamic
  • 672
  • 4
  • 20
  • 1
    See: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – chris Nov 08 '17 at 03:22
  • Not sure how I didn't think of that. Marked as duplicate. Thanks. – Will Hamic Nov 08 '17 at 03:24
  • here is another similar question asked on here: https://stackoverflow.com/questions/1286394/for-loop-in-c-using-double-breaking-out-one-step-early-boundary-value-not-rea hope that helps – D.H. Nov 08 '17 at 03:26

0 Answers0