Unexpected Output when adding two float numbers

前端 未结 3 901
傲寒
傲寒 2020-12-20 22:11

I wrote the following C++ code:

float a, b;
int c;

a = 8.6;
b = 1.4;
c = a + b;

printf(\"%d\\n\", c);

The output is 10.

3条回答
  •  渐次进展
    2020-12-20 22:46

    Floating point numbers are not the same as real numbers and their behavior is quite different.

    Real numbers are infinite, while floating point numbers are finite and can only represent a small subset of all the possible real numbers.

    Since not all real numbers can be represented as floating point, a floating point assignment or operation may give you slightly different results than the same done in the real number space.

    See the wikipedia entry on floating point for an introduction. The section about floating point accuracy is particularly interesting and gives other examples similar to yours.

提交回复
热议问题