Why is adding a small number to the float wrong?

Possible duplicate:
Adding double values ​​is incompatible

int x = 0;
float n = 0;
while ( n != 1 ) {
n += 0.1;
++x;
}

I wonder why this cycle is endless?

+3
source share
1 answer

0.1 cannot be represented exactly in floating point:

printf("%.16f\n", 0.1f);

displayed:

0.1000000014901161

So it nwill never be exactly the same 1.

As @sirlak notes in the comments below, it is almost never worth checking floating point variables for equality like this.

+16
source

All Articles