A float set to 0.1 compares false to 0.1

int main() { float f = 0.1; if (f == 0.1) printf("True"); else printf("False"); } 

I'm just new to c. I do not understand the behavior of the above program. The output is false. Why??

-3
source share
1 answer

0.1 is a literal double .

Since 0.1 cannot be represented exactly in floating point, a float set to 0.1 compares false with a double parameter of 0.1.

Your comparison will behave as intended if you use the literal float : 0.1f (note the suffix f : should not be confused with your variable name):

 float foo /*renamed for clarity*/= 0.1; if (foo == 0.1f){ /*this will compare true*/ 
+7
source

Source: https://habr.com/ru/post/1241247/


All Articles