与浮点数混淆

Par*_*ita 3 c floating-point floating-point-precision floating-point-conversion

int main()
{
  float x=3.4e2;
  printf("%f",x);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

340.000000  // It's ok.

但是如果写x=3.1234e2输出是312.339996x=3.12345678e2输出是312.345673.

为什么输出会像这样?我想如果我写x=3.1234e2输出应该是312.340000,但实际输出是312.339996使用GCC编译器.

Too*_*the 9

并非所有小数都具有精确的二进制等价值,因此它会舍入到最接近的值.

简化示例,

如果您有3位的分数,您可以:

0
0.125
0.25
0.375
...
Run Code Online (Sandbox Code Playgroud)

0.5具有精确的表示,但0.1将显示为0.125.

当然,真正的差异要小得多.