【发布时间】:2015-06-05 05:26:20
【问题描述】:
谁能解释一下 printf 中的[.precision] 如何与说明符“%g”一起工作?我对以下输出感到很困惑:
double value = 3122.55;
printf("%.16g\n", value); //output: 3122.55
printf("%.17g\n", value); //output: 3122.5500000000002
我了解到%g 使用最短的表示。
但以下输出仍然让我感到困惑
printf("%.16e\n", value); //output: 3.1225500000000002e+03
printf("%.16f\n", value); //output: 3122.5500000000001819
printf("%.17e\n", value); //output: 3.12255000000000018e+03
printf("%.17f\n", value); //output: 3122.55000000000018190
我的问题是:为什么%.16g 给出确切的数字而%.17g 不能?
似乎 16 位有效数字是准确的。谁能告诉我原因?
【问题讨论】:
-
在 IEEE 浮点数中永远不会这样。
-
@user35443 实际上是 IEEE 浮点表示 (ieee-754) 导致了这种情况。