In a book I am currently reading, there is this excerpt:
You can also use a floating-point value as a loop counter. Here's an example of a
forloop with this kind of counter:double a(0.3), b(2.5); for(double x = 0.0; x <= 2.0; x += 0.25) cout << "\n\tx = " << x << "\ta*x + b = " << a*x + b;This code fragment calculates the value of
a*x+bfor values ofxfrom0.0to2.0, in steps of0.25; however, you need to take care when using a floating-point counter in a loop. Many decimal values cannot be represented exactly in binary floating-point form, so discrepancies can build up with cumulative values. 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 poorly-designed loop never ends:for(double x = 0.0 ; x != 1.0 ; x += 0.2) cout << x;The intention with this loop is to output the value of
xas it varies from0.0to1.0; however,0.2has no exact representation as a binary floating-point value, so the value ofxis never exactly1. Thus, the second loop control expression is always false, and the loop continues indefinitely.
Can someone please explain how the first code block runs while the second doesn't?