混乱浮点数 [英] Confusion with floating point numbers

查看:144
本文介绍了混乱浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
  float x=3.4e2;
  printf("%f",x);
  return 0;
}

输出:

340.000000  // It's ok.

但如果写 X = 3.1234e2 输出 312.339996 ,如果 X = 3.12345678e2 输出 312.345673

为什么像这样的输出?我想,如果我写的 X = 3.1234e2 输出应为 312.340000 ,但实际产量为 312.339996 使用GCC编译器。

Why are the outputs like these? I think if I write x=3.1234e2 the output should be 312.340000, but the actual output is 312.339996 using GCC compiler.

推荐答案

不是所有的小数具有确切的二进制数,因此被四舍五入到最接近的数值。

Not all fractional numbers have an exact binary equivalent so it is rounded to the nearest value.

简单的例子,

如果您有部分3位,你可以有:

if you have 3 bits for the fraction, you can have:

0
0.125
0.25
0.375
...

0.5具有精确重新presentation,但0.1将显示为0.125

0.5 has an exact representation, but 0.1 will be shown as 0.125.

当然,真正的差别要小得多。

Of course the real differences are much smaller.

这篇关于混乱浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆