c - 为什么在 C 中两个 float 的相加是不正确的?

标签 c floating-point

我在添加两个浮点数时遇到问题。
代码如下:

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

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

为什么输出结果是 450002816.000000? (正确的应该是 450002832。)

最佳答案

浮点数在 C 中没有精确表示 - 请参阅 http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computershttp://en.wikipedia.org/wiki/Single_precision ,因此使用浮点数进行计算只能给出近似结果。

这对于较大的值尤其明显,因为可能的差异可以表示为值的百分比。在添加/减去两个值的情况下,两者(以及结果)的精度都会变差。

关于c - 为什么在 C 中两个 float 的相加是不正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7334233/

相关文章:

floating-point - 如何将复数的虚部设置为零?

c - 在 Visual Studio 2005 中使用 WinDDK 测试实用程序

c - 在 C 中显示奇数次数字

c++ - 类型 'float'和 'const c'的无效操作数

r - R中非常小数的算术

floating-point - 在 MiniZinc 中我该如何解决这个错误?

带有 float 的 Java msgpack 类崩溃

c++ - Cuda:访问冲突写入位置 0x0000000000000000

c - 害怕只从我第一次运行程序时开始阅读

c - 使用 sigqueue 和 SIGUSR1 将子 pid 发送给父亲