0

Why this code gives NOK ?

int main()
{
    float f = 0.1;

    if (f == 0.1) {
        printf("OK\r\n");
    } else {
        printf("NOK\r\n");
    }
    return 0;
}
perencia
  • 1,498
  • 3
  • 11
  • 19
  • 3
    What happens when you change `float` to `double` ? Your value `0.1` is a double literal, fyi. – WhozCraig Dec 15 '17 at 20:03
  • Coercion so change your float to a double right now your 0.1 is actually truncated into being 0. – Boschko Dec 15 '17 at 20:06
  • 1
    Never compare floats or doubles for equality. – Lee Daniel Crocker Dec 15 '17 at 20:14
  • 2
    @Boschko No, it's not being "truncated into being 0". It's a `float` being compared to a `double`. It will be converted to a double `0.1`, but the value will not be as accurate as a true double `0.1`. There is no integer math involved. – Tom Karzes Dec 15 '17 at 20:14
  • @TomKarzes Ahhh I see – Boschko Dec 15 '17 at 20:37
  • @Boschko Why the conversion will not be as accurate as a true double `0.1` ? – perencia Dec 15 '17 at 20:45
  • @perencia because you end up doing whats called explicit type conversions. since some numbers can be represented more exactly in binary than others. You can see the difference in 0.125 (1/8, eight is a power of two) and 0.1 (1/10, ten is not a power of two). The former has more (decimal) digits, therefore if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal. – Boschko Dec 15 '17 at 21:03
  • @LeeDanielCrocker There are times when it's appropriate to compare floating-point values for equality, for instance when implementing fabs(). But also your advice is useless in itself. You forgot to provide the sempiternal recommendation to compare up to epsilon, and like everyone who gives that recommendation, you did not explain how to choose said epsilon. – Pascal Cuoq Dec 21 '17 at 21:08
  • Fair complaint about not giving complete advice. But `fabs()` is not really a unique exception to the rule--comparing with 0 is the real exception, which is OK in many contexts, such as fabs(). – Lee Daniel Crocker Dec 21 '17 at 21:39

0 Answers0