Infinite loop

I have written a program -

#include <iostream>

using namespace std;

int main()
{
float D;

D=0.1;

while ( 1.0-D != 0.0 ) {
cout << D << endl;
D=D+0.1;
}

return 0;
}

On executing, while loop becomes an infinite loop. The answer that i got is, there is the problem with precision. But if i use this condition in if statement that it returns correctly true or false.
Try to modify the condition in ( int(10-D*10) != 0 )
My question is why it is an infinite loop.
Because the float is wrong for a little value
instead of getting 0 (from 1.0-D) you will get something like -1.19209e-7 (this is what I get)

(Same problem as in http://www.cplusplus.com/forum/general/4920/ )
Last edited on
http://www.cplusplus.com/forum/articles/3827/
(I'm starting to wonder if anyone here even bothers to look for a solution before posting)
Very good article. Personally I think we need an article that suggests to solve problems in the integer domain if at all possible and resort to floating point only if absolutely unavoidable.
Ok Bazzy! but why it works correctly with if statement....
Very good article

Thanks ;-)

Personally I think we need an article that suggests to solve problems in the integer domain if at all possible

I doubt that it would be of much use - I wonder why I wrote that other article in the first place. Those who could use it don't seem to be willing to read it, as seen from the post above...
Topic archived. No new replies allowed.