analysing bug

#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;
}

//above code has a bug due to which while loop is executing infinitely.i dont know what the problem is?
In the representation of fractions, there are truncation errors. Representing 0.1 as a float or even double is an approximation.

1
2
3
4
while ( 1.0-D > 0.05 ) {
      cout << D << endl;
      D=D+0.1;
}


You have to make your comparison within some tolerance as above.
You'd probably be better off doing it this way:

1
2
   for( int D_times_ten = 9; D_times_ten; --D_times_ten ) 
      cout << ( D_times_ten / 10.0 ) << endl;


Floating point is very hard to get right and most people don't understand anything about round-off error. See:

http://docs.sun.com/source/806-3568/ncg_goldberg.html
I think your while loop is saying while 1.0-D is not assigned 0.0 when you really mean equalls:
ie. while(1.0-D !==0.0)
buffbill: Yes, the single equals is the assignment operator and is used for assigning, but the correct syntax for not equal to is "!=" as he has it in his original code. There is no such thing as a comparator that says "not assigned to" (well, unless you want to count NULL).
Topic archived. No new replies allowed.