为什么golang常数可能会溢出int64而不是float64?

问题描述 投票:-3回答:2

为什么在下面的代码片段中常量总是溢出int64而不是float64?

package main

import "fmt"

const Big = 1 << 100

func needInt(x int64) int64 {
    return x / 10
}

func needFloat(x float64) float64 {
    return x / 10
}

func main() {
    // will produce:
    // ./prog.go:17:21: constant 1267650600228229401496703205376 overflows int64
    //fmt.Println(needInt(Big))

    // works fine
    fmt.Println(needFloat(Big))

    // will produce:
    // ./prog.go:20:13: constant 1267650600228229401496703205376 overflows int
    //fmt.Printf("Type: %T Value: %v\n", Big, Big)

}

https://play.golang.org/p/0CB1eiXG1AP

go floating-point integer constants integer-overflow
2个回答
1
投票

您的数字大约在1e30左右,这太小了而无法溢出float64。 math.MaxFloat64约为1.8e308:const x float64 = 1e308 // ok const y float64 = 1e309 // constant 1e+309 overflows float64

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

1
投票
因为int类型记录的数字具有固定的精度,而float类型则没有。 float类型可以存储比相同宽度的int类型大得多和小得多的数字,但是float类型这样做存储的是精度方面的损失:最低有效位会丢失。它是科学计数法的二进制等效形式,其中尾数四舍五入到一定数量的有效数字。
© www.soinside.com 2019 - 2024. All rights reserved.