For loop with Floating Point Loop Counter - pp. 150
On pp. 150 in chapter 3 - the book states (In the section - "Floating Point Loop Counters", in the middle of the second paragraph where the author tries to provide an example of a for loop which would never terminate):
"This means that you should not code a for loop such that ending the loop depends on a floating-point loop counter reaching a precise value. For example, the following pporly-designed loop never ends.
for (double x = 0.0 ; x!= 1.0 ; x+= 0.2)
cout <<x;
I tried it but the loop actually ends.
I got the following output: 00.20.40.60.8.
Then I added an endl to get slightly better output and I got:
0
0.2
0.4
0.6
0.8
--
Here is my code:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
for (double x = 0.0; x != 1.0; x += 0.2)
cout << x << endl;
return 0;
}
----
I have submitted this to the book team as well. Any comments on this? Has anyone tried it out? I am essentially not able to substatiate the authors claim that the loop would continue forever. Thanks much.
|