【问题标题】:Why there's no precision error when printing 0.1 as a double with many digits after point?为什么在点后将 0.1 打印为带有许多数字的双精度时没有精度错误?
【发布时间】:2020-04-05 01:40:23
【问题描述】:

下面的函数(用 Kotlin 编写)

fun main() {
   println ("%.20f".format(0.1f))
   print ("%.100f".format(0.1))
}

打印

0.10000000149011612000
0.1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

如果 0.1 不能完全表示为二进制分数,为什么双精度版本没有精度错误?

【问题讨论】:

    标签: kotlin floating-point double precision


    【解决方案1】:

    在 Java 中,float 的精度约为 7 位,而 double 的精度约为 16。
    即使您告诉它打印 20 位或 100 位数字,实际值仍受给定精度的限制。 double 也有错误,虽然较小。

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多