0
    #include <iostream>
using namespace std;

int main() {
    float f =9.58;
    if(f<9.58)
    {
        cout<<"T";
    }
    else
    {
        cout<<"F";
    }
    return 0;
}

As per the logic, 9.58 is equal to 9.58 so it should return false but it is returning true.

Bikramjit Das
  • 54
  • 1
  • 1
  • 5
  • 2
    You should be careful with your literals `float f = 9.58f` and `if (f < 9.58f)` – Cory Kramer Apr 06 '21 at 14:20
  • 2
    I haven't tried it, but my intuition is that you have a low-precision float compared to a high-precision double. – Wyck Apr 06 '21 at 14:20
  • Try `0.5` or `0.25` instead of `9.58`. If the return value is `false`, then you will get a taste of binary floating point math, and what can be represented exactly in binary floating point. – PaulMcKenzie Apr 06 '21 at 14:23
  • @Wyck I did and with 9.58f in both places it returns false as expected. – Borgleader Apr 06 '21 at 14:24
  • Compare the binary representation of [float](https://www.binaryconvert.com/result_float.html?decimal=057046053056) to [double](https://www.binaryconvert.com/result_double.html?decimal=057046053056) and I imagine when the float gets promoted to double for comparison, it can't correctly estimate all those missing bits (they're probably zero-filled, which is why the float is less than the double). – Wyck Apr 06 '21 at 14:25
  • Its precision loss, https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose-precision?view=msvc-160 explains why comparing floats directly is not a good idea. – Niteya Shah Apr 06 '21 at 14:26
  • 1
    you should also be able to see this by doing ``cout.precision(32);std::cout << f << std::endl;`` and see that 9.58 is actually stored as a value less than 9.58. – Niteya Shah Apr 06 '21 at 14:27

0 Answers0