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

前端 未结 3 1463
鱼传尺愫
鱼传尺愫 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条回答
  • 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).

    0 讨论(0)
  • 2021-01-19 08:30

    Floating-point values cannot represent all integer values.

    Remember that single-precision floating-point numbers only have 24 (or 23, depending on how you count) bits of precision (i.e. significant figures). So as values get larger, you begin to lose low-end precision, which is why the result of your calculation isn't quite "correct".

    0 讨论(0)
  • 2021-01-19 08:31

    From wikipedia

    Single precision, called "float" in the C language family, and "real" or "real*4" in Fortran. This is a binary format that occupies 32 bits (4 bytes) and its significand has a precision of 24 bits (about 7 decimal digits).

    So your number doesn't actually fit in float. You can use double instead.

    0 讨论(0)
提交回复
热议问题