-1

When I run this code it prints False. it's not clear to me

#include <stdio.h>
    int main()
    {
        float f = 0.1;
        if (f == 0.1)
            printf("True");
        else
            printf("False");
    }

I expect this code to print out True instead of False

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • generally speaking you should use `double` not `float` – erik258 Mar 06 '23 at 22:18
  • 2
    Note that `0.1` cannot be exactly represented in either a `float` or a `double` variable. But if you stick to the same floating point type, there can be equality of these imprecise values. My compiler warns me that the `double` value `0.1` is being truncated to `float`. – Weather Vane Mar 06 '23 at 22:21
  • 2
    Typically the nearest representable `float` value to `0.1` is `0.100000001490116119384765625`, while the nearest `double` value is `0.1000000000000000055511151231257827021181583404541015625`. Those are the values you're comparing. – Keith Thompson Mar 06 '23 at 23:10

1 Answers1

5

0.1 is a double constant. In float f = 0.1;, the double value is implicit converted to float. The float and double types have different precisions, so the conversion incurs a small rounding error. In consequence, the float value stored in f is not equal to the double value of 0.1.

If you change 0.1 to 0.1f in both places it appears, the program will print “True”.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Thanks a lot for your helpful answer. But, please can you explain to me the semantics behind `0.1f`? – محمود خالد Mar 06 '23 at 22:26
  • @محمودخالد: I suggest that you read about [suffixes in floating constants](https://en.cppreference.com/w/c/language/floating_constant#Suffixes). The `f` suffix simply means that the floating constant is of type `float` instead of `double`. – Andreas Wenzel Mar 06 '23 at 22:30