0

I executed the following C++ code and get the answer "Not the same? Weird.....". Originally I expected to get "Of course, they are the same!!!". I was using Dev-C++ 5.11.

#include <iostream>
using namespace std;

int main() {
    float p;
    p = 0.3;
    if ((p-0.3)==0)
        cout << "Of course, they are the same !!!\n";
    else
        cout << "Not the same? Weird.....\n";
    return 0;
}
J. H. Jeng
  • 31
  • 2
  • 3
    `0.3` is a double not a float – Mat Jun 17 '22 at 10:00
  • Note that 0.3 is not exactly representable in neither single nor double precision IEEE 754 format. You can try it, for example, here: https://baseconvert.com/ieee-754-floating-point. – Daniel Langr Jun 17 '22 at 10:15

1 Answers1

1

As Mat points out, the problem here is that 0.3 is a double. And (double)(float)0.3 != 0.3. You lose precision when casting 0.3 to float. Casting it back does not magically undo the rounding.

MSalters
  • 173,980
  • 10
  • 155
  • 350