-1

why the following snippet

int i = 30;
int p = 0.7f * i;
printf("p is %d\n", p);

gives 20 instead of 21 on vc++ 2008 express ? I know it's an old compiler!

AlessioR
  • 3
  • 1
  • The value `0.7` cannot be exactly represented in a floating point variable. Please see [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) Note that `20.999999` will be truncated to `20`. – Weather Vane May 31 '20 at 12:37
  • Thank you for the links, but I was more curiose about what Microsoft should have changed in VC++ 2019, because it give the correct mathematical result. – AlessioR May 31 '20 at 16:47
  • Do you mean with that *exact code*, or when you `printf` the floating point value? Perhaps 2008 had a slightly different floating point implementation. – Weather Vane May 31 '20 at 16:49
  • good point! But I do not printf the floatint point value, it is already casted to int. I think I can answer myself looking at assembler produces by both compilers. – AlessioR May 31 '20 at 16:54
  • Perhaps the older PC uses an 80x87 FPU. The point is, you not should rely on accuracy from floating point arithmetic. – Weather Vane May 31 '20 at 16:57
  • Please see [Change floating point rounding mode](https://stackoverflow.com/questions/6867693/change-floating-point-rounding-mode) and MS [_control87](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/control87-controlfp-control87-2?redirectedfrom=MSDN&view=vs-2019). – Weather Vane May 31 '20 at 17:08

1 Answers1

0

The number 0.7 is not representable in the binary-based floating-point format your compiler uses for float. When the decimal numeral “0.7” is converted to float, the result is the nearest representable value. That is a number slightly below 0.7.

Multiplying that by 30 produces a number slightly below 21, and converting it to int with truncation produces 20.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312