2
#include <stdio.h>
#include <float.h>
#include <stdlib.h>

int main() {
    float x = 3.8, y = 5.2;
    int a, b, c;
    float d = x + y;
    a = d;
    b = (int)(x + y);
    c = (int)(3.8 + 5.2);
    printf("a=%d,b=%d,c=%d\n", a, b, c);
    return 0;
}

The result is

9,8,9

And I thought 9,9,9 is the right output, please tell me, why.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Hongyuan
  • 100
  • 6
  • For me it's `9,9,9` https://wandbox.org/permlink/Uk8QhbAymYacOIvs – hellow Sep 05 '18 at 09:29
  • 3
    In `3.8 + 5.2` you are adding two `double` values. In `x + y` you are adding two `float` values. 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) – Weather Vane Sep 05 '18 at 09:29
  • Found the cause.When I remove gcc flag -std=c11,it print 9,9,9.When I add -std=c11,it print 9,8,9. – Hongyuan Sep 06 '18 at 01:43
  • Reopened. This is not the normal floating point inaccurate question. There are a variety of reasons behind the output that I feel the duplicate does not cover. – Bathsheba Sep 06 '18 at 06:46

1 Answers1

5

In a single precision IEEE754 (the float scheme most likely used on your platform), x is 3.7999999523162841796875 and y is 5.19999980926513671875. The sum of those is a little under 9, and the cast to int truncates the result. (Note that float x = 3.8 actually truncates the double constant 3.8 to a float: 3.8f is a constant of type float.)

But 3.8 + 5.2 is computed in double precision. In double precision IEEE754 3.8 is 3.79999999999999982236431605997495353221893310546875 and 5.2 is 5.20000000000000017763568394002504646778106689453125. This sums to just over 9, and so the int truncation recovers 9.

The fact that a and b are different is due to floating point evaluations not being strict on your compiler. You should be able to change its settings should you need to.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483