doushang3352 2017-11-09 23:22
浏览 54
已采纳

为什么Go中带文字的浮点乘法与变量之间有区别?

Why are the following unequal in Go? Is this a bug, or is it by design? If it's by design, why does this occur and is this type of behavior documented anywhere?

https://play.golang.org/p/itEV9zwV2a

package main

import (
    "fmt"
)

func main() {
    x := 10.1

    fmt.Println("x == 10.1:        ", x == 10.1)
    fmt.Println("x*3.0 == 10.1*3.0:", x*3.0 == 10.1*3.0)
    fmt.Println("x*3.0:            ", x*3.0)
    fmt.Println("10.1*3.0:         ", 10.1*3.0)
}

Produces:

x == 10.1:         true
x*3.0 == 10.1*3.0: false
x*3.0:             30.299999999999997
10.1*3.0:          30.3

Note that the same floating point math is being performed, just with different syntax. So why is the result different? I would expect 10.1*3.0 to equal 30.29999... as in the x*3.0 example.

  • 写回答

2条回答 默认 最新

  • duanfu7004 2017-11-09 23:37
    关注

    Constants and number literals in Go are untyped and have unlimited precision. The moment it has to be stored as a specific type, the bounds of that type apply. So when you declare x := 10.1, that literal is converted into a float and loses some precision. But when you specifically do 10.1*3.0 these have their full precision.

    See the "Floats" header in this article. https://blog.golang.org/constants

    Numeric constants live in an arbitrary-precision numeric space; they are just regular numbers. But when they are assigned to a variable the value must be able to fit in the destination. We can declare a constant with a very large value:

    const Huge = 1e1000 
    

    —that's just a number, after all—but we can't assign it or even print it. This statement won't even compile:

    fmt.Println(Huge)
    

    The error is, "constant 1.00000e+1000 overflows float64", which is true. But Huge might be useful: we can use it in expressions with other constants and use the value of those expressions if the result can be represented in the range of a float64.

    How it actually does this, especially in the given Huge case, I do not know.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?