int i = 0;
double n = 1.24;
for (; int(n) != n; i++) {
n *= 10;
}
Why does it enter an infinite loop? Shouldn't it stop after two loops?
int i = 0;
double n = 1.24;
for (; int(n) != n; i++) {
n *= 10;
}
Why does it enter an infinite loop? Shouldn't it stop after two loops?
1.24
cannot be represented exactly as a double
. If you examine the initial value of n
, you'll see that it is 1.239999999999999991118215802998747...
As to why the loop never stops, once n
exceeds the value of the largest double
, it is automatically converted to +Infinity
, which is a special floating-point value. Once you've reached that point, n
stops changing and int(n) != n
can never be satisfied.
Because double is not exact representation of number and condition int(n) == n never reached. Read this http://en.wikipedia.org/wiki/Floating_point
I have tried it, and it stops for after two loops. I have used gcc. I changed int(n) to (int)n
The infinite loop happens due to some rounding error, try to check the difference between (int)n and n
In general, do not use equally to check equality with double. Use instead
if (fabs(a-b)<1e-10) //instead of a==b