0

I got a question to find the output of below code snippet

int main(int argc, char const *argv[])
{
float a=0.7;
if(a<0.7)
 std::cout<<"yes";

else
 std::cout<<"no";
}

At first look, like everyone my answer was "no" because 0.7 is not less than 0.7. But when i run it, output was "yes". I found an explanation about this which says C++ internally takes 0.7 as double value and here actually it is checking whether 0.700 < 0.7ff which will be true. So i tried the same with another value 0.5. But then this program had "no" as output. Why it is so? Doesn't it really check whether 0.500<0.5ff?, or all my understanding about it is wrong?

Hari Krishnan
  • 5,992
  • 9
  • 37
  • 55
  • 1
    `0.5` happens to be the same as `1/2` which *is* exactly representable in binary. – Bo Persson Aug 27 '17 at 14:46
  • 1
    In addition to @BoPersson's comment: Any value that contains (positive and/or negative) powers of 2 (up to a certain limit defined by the number of bits in the significand) can be exactly represented, so 0.5 (2^-1), but also 0.75 (2^-1 + 2^-2), 3.375, etc. But 0.7 is never exactly representable in powers of 2, so it must be approximated. The closest approximation of 0.7 (double) seems to be slightly lower than the closest approximation of 0.7f (float). – Rudy Velthuis Aug 27 '17 at 15:29
  • Just because the `float` approximation of 7/10 happens to be less than the `double` approximation of 7/10 does not mean that the same is true for every rational number. It's obviously nor true for 5/10 because that one is represented exactly as `float` and as `double`, but there are other rationals that are not represented exactly as either `float` or `double` for which the `float` representation is greater than the `double` representation. – Pascal Cuoq Aug 28 '17 at 09:48

0 Answers0