Why this for is infinite

i wrote this code:
1
2
for(double x = 0.0; x != 1.0; x += 0.1)
cout << x << endl;


it was suppose to output the value from 0 to 1 but instead i got infinite loop.

So why is that?

And how can i fix it?
Last edited on
closed account (28poGNh0)
Check out again It s working well
I tried it on my compiler and it worked perfectly.
can you please put all the code here?
i am sorry guys i meant x != 1.0 not x <= 1.0 i fixed it now
It's because of rounding errors. You can't rely on floating point numbers to be exactly equal to a number.

double x = 0.1; would be 0.100...001, which is not equal to 0.1 but is slightly larger.
Last edited on
thanks Ikaron for the answer that helped.
Topic archived. No new replies allowed.