Why "for( i = 0.1 ; i != 1.0 ; i += 0.1)" doesn't break at i = 1.0?
c, floating-point
Solution
This is a typical question for homework.
The Problem is that the 0.1 cannot be exactly stored in a float better check for <= 1.0
However this just works only for a very limited range like Cthulhu said. I missed that problem completely. Of cause it is better to use `int` and divide its value later.
Problem
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.