Why does the addition of two float numbers is incorrect in C?

前端 未结 3 1465
鱼传尺愫
鱼传尺愫 2021-01-19 08:03

I have a problem with the addition of two float numbers. Code below:

float a = 30000.0f;
float b = 4499722832.0f;

printf(\"%f\\n\", a+b);

3条回答
  •  梦毁少年i
    2021-01-19 08:26

    Float are not represented exactly in C - see http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers and http://en.wikipedia.org/wiki/Single_precision, so calculations with float can only give an approximate result.

    This is especially apparent for larger values, since the possible difference can be represented as a percentage of the value. In case of adding/subtracting two values, you get the worse precision of both (and of the result).

提交回复
热议问题