为什么在下面的代码片段中常量总是溢出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)
}
您的数字大约在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
int
类型记录的数字具有固定的精度,而float
类型则没有。 float
类型可以存储比相同宽度的int
类型大得多和小得多的数字,但是float
类型这样做存储的是精度方面的损失:最低有效位会丢失。它是科学计数法的二进制等效形式,其中尾数四舍五入到一定数量的有效数字。