0
#include <stdio.h>
int main()
{
    float f; 
    f = 0.4;
    if(f<0.4)
       printf("It is less");
    if(f>0.4)
       printf("It is greater");
    if(f==0.4)
       printf("It is equal");
}

I am not able to get why the output is showing "It is greater".

I get that 0.4 converted to binary representation is 0x3ECCCCCD, which is 4.000000059604644775390625E-1. The doubt is if f stores this rounded value, why 0.4 in the comparison is exact. If both f and 0.4 gets rounded, the output should have been "It is equal".

I tried with f = 0.5, it is showing "It is equal".

While f=0.9, it is showing "It is less".

Please take note that there is no arithmetic at all.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

1 Answers1

4

While f is a float, all your literals are double.

If you ask nicely, the compiler will even warn you about the assignment:

warning: conversion from 'double' to 'float' changes value from '4.0000000000000002e-1' to '4.00000006e-1f' [-Wfloat-conversion]

Unfortunately, it cannot warn about the comparison, because simply widening the smaller type is nearly always what you want, and was thus codified.

Anyway, floating-point math is dangerous and surprising for the uninitiated:
Is floating point math broken?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • What would happen if OP had `f = 0.4f` in assignment, and `if(f<0.4)` in comparison? It would be a failure of the same type, but would the compiler emit any warning then? (I suspect not; cannot check) – anatolyg Nov 27 '18 at 19:10
  • @anatolyg Yes, there are limitations to automatic checking: http://coliru.stacked-crooked.com/a/c359e04ea5623d9c – Deduplicator Nov 27 '18 at 19:14