我正在尝试使用以下代码打印浮点值 299792450
:
#include <stdio.h>
int main()
{
printf("%f\n", 299792450.0f);
return 0;
}
根据 IEEE 754 Calculator ,这是 binary32 格式的可精确表示的浮点值。但是我在输出中得到了另一个值:
$ ./a.out
299792448.000000
为什么它不等于 299792450
?我希望它是 299792450
,因为它是可以精确表示的,并且不应该有精度损失。
最佳答案
假设 float
是一个 IEEE754 单精度 float ,299792450 不能被精确表示。
此值至少需要 28 位精度,但 float
最多有 24 位精度。因此,该值会四舍五入到可以表示的最接近的可能值。
如果您使用具有 53 位精度的 double
,您将看到准确的值。
printf("%f\n", 299792450.0);
关于我可以在不损失精度的情况下打印完全可表示的 float 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972809/