0
main()
{

  float f=0.7;
  if(0.7>f)
  printf("Hi");
  else
  printf("Hello"):
}

When I compile this program output comes out to be Hi.

Can someone please explain the scenerio how 0.7>0.7 is true? Is this due to fact that 0.7 used in if statement is a double and f is a float?
Even if it is double still its value is 0.7 difference created is just that in case of double it is stored in 8 byte while in case of float it is stored in 4 byte. But I think it does not matters how big is your container when the value stored in container is equal. So 0.7 can never be greater than f. So according to me it should result in Hello. then why Hi is the output?

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
user3335653
  • 133
  • 1
  • 8
  • 7
    There are hundreds of duplicates of this, with different float values. Long story short, since `0.7` cannot be represented exactly, and because `0.7` is treated as a `double`, not as a `float`, the two representations differ slightly, resulting in the behavior that you see. Change `0.7` to `0.7F` to make it work correctly. You wouldn't see this behavior with numbers that have an exact representation as `double` and `float`, for example, `0.5`, `0.25`, `0.125`, and so on. – Sergey Kalinichenko Feb 26 '14 at 13:50
  • http://perso.ens-lyon.fr/jean-michel.muller/goldberg.pdf is strongly recommended to be read, at least first pages – Manuel Selva Feb 26 '14 at 13:53
  • can you please explain me a little more.i just change the value from 0.7 to 0.5 and yes you are right output comes out to be hello. – user3335653 Feb 26 '14 at 13:59

2 Answers2

1

The container does makes the difference here. The idea is how these values are stored and then retrieved. If you use a number that can be converted back to exact decimal value. You may see the difference.

Smitt
  • 178
  • 7
1

Use this and see the output:

 float f=0.7f;

If you define float f = 0.7, it is stored as manttisa and exponent. It depends on the precision. So in this case .7 will be less than .7. If you define 0.7f it will be equal to 0.7.

Rahul
  • 3,479
  • 3
  • 16
  • 28
  • and if I take f=0.5 then output will be hello.why is 0.5 is not stored as mantissa and exponent. – user3335653 Feb 26 '14 at 15:48
  • @user3335653 you can represent `0.5 in binary as .10000000` and `.7 will be 0.1011001100110011001100110011001100110011001100110011`. It depends on how many bits are being used for `manttisa` and how many for `exponenet`. In `.7` if some of the `last bit` are not stored that will be less than `.7`, while it is not in the case of `.5`. – Rahul Feb 27 '14 at 05:55