I had an exam today in C and I was asked a question similar to:
What is wrong with this program:
for( x = .1 ; x != 1.0 ; x += .1) printf("%f\n", x);
I couldn't solve it and since I had to write something I marked .1
as an error. But, when I went back home, I run this program, It turned out that it doesn't break when x
equals to 1.0
and stuck in an infinite loop:
$ cat exam.c
#include <stdio.h>
int main(int argc, char **argv)
{
float x;
for(x = .1 ; x != 1.0 ; x += .1)
printf("%f\n", x);
return 0;
}
$ gcc exam.c -o exam
$ ./exam
0.100000
0.200000
0.300000
0.400000
0.500000
0.600000
0.700000
0.800000
0.900000
1.000000 <- ?
1.100000
1.200000
1.300000
1.400000
1.500000
....
Could someone please explain why this is happening.