Why this for is infinite

Mar 20, 2013 at 8:05am
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 Mar 20, 2013 at 8:18am
Mar 20, 2013 at 8:10am
closed account (28poGNh0)
Check out again It s working well
Mar 20, 2013 at 8:14am
I tried it on my compiler and it worked perfectly.
can you please put all the code here?
Mar 20, 2013 at 8:19am
i am sorry guys i meant x != 1.0 not x <= 1.0 i fixed it now
Mar 20, 2013 at 8:57am
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 Mar 20, 2013 at 8:58am
Mar 20, 2013 at 5:51pm
thanks Ikaron for the answer that helped.
Topic archived. No new replies allowed.