我写了以下程序:
#include<stdio.h>
int main(void)
{
float f;
printf("\nInput a floating-point no.: ");
scanf("%f",&f);
printf("\nOutput: %f\n",f);
return 0;
}
我在Ubuntu上,用GCC编译了上面的程序。下面是我想要查询的示例运行和输出:
Input a floating-point no.: 125.1
Output: 125.099998
为什么精度会发生变化?
发布于 2011-06-30 17:10:50
因为数字125.1是impossible to represent exactly with floating-point numbers。这在大多数编程语言中都会发生。如果您想打印带有一个小数的数字,请使用printf("%.1f", f);
,但请注意:数字本身并不完全等于125.1。
发布于 2011-06-30 17:27:20
首先考虑固定点表示法。
2^3=8 2^2=4 2^1=2 2^0=1 2^-1=1/2 2^-2=1/4 2^-3=1/8 2^-4=1/16
如果我们想要表示一个分数,那么我们将位设置在点的右侧,因此5.5
被表示为01011000
。
但如果我们想要表示5.6
,就没有确切的分数表示。我们能得到的最接近的是01011001
== 5.5625
1/2 + 1/16 = 0.5625
2^-4 + 2^-1
发布于 2011-06-30 17:11:37
因为它是125.1的最接近的表示,记住单精度浮点数只有32位。
https://stackoverflow.com/questions/6532502
复制相似问题