AnTiDoD,
Thank you for posing the question. You have prompted me to think a little deeper to explore the concepts behind the code. I had not attempted to compile and run the code. I just played computer with it.
I compiled and ran the code and discovered that it
does loop endlessly. Here is the code I wrote to test for failure to end the loop:
Code:
//sample_loop.cpp
//does this terminate?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
for (double x = 0.0; x!= 1.0; x+= 0.1)
cout << x << endl;
return 0;
}
I believe the problem lies in the fact that 0.1 does not have an exact binary floating point equivalent. There are only approximations. This creates a situation where x will
never equal
exactly 1.0; therefore, the loop never satisfies the condition and continues until terminated manually.
If I understand the concept properly, the only floating point values which will result in a loop which terminates as desired must result in a value which is an
exact power of two. Increments of 0.5, 0.25, 0.125, ... would terminate in the above code.
I am currently working my way through Chapter 3, but had not reached the
FloatingPoint Loop Counters topic prior to now. My attempt to resolve the loop termination problem prompted me to read ahead of my current progress to find an answer.
Did I come up with the correct answer to your question?
Quote:
Next code never stopped, and you known why?) I know)

regards,
drpepper