代码之家  ›  专栏  ›  技术社区  ›  Homam

为什么0.1*10-1不等于0?[副本]

  •  0
  • Homam  · 技术社区  · 14 年前

    可能重复:
    Why is floating point arithmetic in C# imprecise?

    Console.WriteLine(0.5f * 2f);       // 1
    Console.WriteLine(0.5f * 2f - 1f);  // 0
    
    Console.WriteLine(0.1f * 10f);      // 1
    Console.WriteLine(0.1f * 10f - 1f); // 1.490116E-08
    

    为什么 0.1f * 10f - 1f 最终成为 1.490116E-08 ( 0.0000001490116 )?

    6 回复  |  直到 7 年前
        1
  •  4
  •   user166390user166390    14 年前

    Wiki: Floating Point . 浮点/双精度/十进制 相对精度 类型。并不是所有的值(其中有无限多个)都可以精确地存储。你看到的是失去准确性的结果。这就是为什么它几乎总是正确的使用 |a - b| < small_delta 用于浮点比较。

        2
  •  1
  •   icyrock.com    14 年前

    由于浮动操作不精确,请查看以下内容:

    部分 Some other computer representations for non-integral numbers . 0.1不能在基2中有限地表示。

        4
  •  1
  •   Lucero    14 年前
        5
  •  0
  •   Blindy    14 年前

    简单,近似累加。

        6
  •  0
  •   lijie    14 年前

    0.5完全可以用浮点表示,所以0.5*2=1。

    然而,0.1不能精确地表示,因此0.1*10不完全是1。