0

This is a simple code which should have printed "No" , but its printing "Yes". It works fine if I use double instead of float Or compare digits upto 1 decimal place. I am using online C++14(gcc+14) compiler here. Why is this happening?

#include <iostream>
using namespace std;

int main() {
    float s= 10.11;
    cout<<(( s < 10.11) ? "Yes": "No")<<endl;
    return 0;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Suryansh Singh
  • 1,123
  • 7
  • 15
  • 1
    [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) and [Floating point comparison `a != 0.7`](https://stackoverflow.com/questions/6883306/floating-point-comparison-a-0-7) – David C. Rankin Apr 03 '21 at 08:45
  • 1
    The literal value `10.11` also has type `double`. A `double` can represent values that a float cannot, so converting a `double` to a `float` can lose precision. `10.11` is also a value that cannot be represented in any floating point type with a radix-2 mantissa - which includes most real-world floating point types (try to represent 10.11 as the sum of positive and negative powers of two to see why - the explanation is the same that one-third cannot be represented exactly in base 10). – Peter Apr 03 '21 at 08:50

0 Answers0