【发布时间】:2019-10-31 02:25:04
【问题描述】:
在 A Tour of Go 中,Numeric Constants 部分的代码是
package main
import "fmt"
const (
// Create a huge number by shifting a 1 bit left 100 places.
// In other words, the binary number that is 1 followed by 100 zeroes.
Big = 1 << 100
// Shift it right again 99 places, so we end up with 1<<1, or 2.
Small = Big >> 99
)
func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 { return x * 0.1 }
func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
fmt.Println(Big * 0.1) //one
fmt.Println(Big / 10) //two
}
fmt.Println(Big*0.1) 输出1.2676506002282295e+29,
但是fmt.Println(Big / 10) 抛出错误:constant 126765060022822940149670320537 overflows int,
它们之间有什么区别。
【问题讨论】:
-
请阅读blog.golang.org/constants。总结:常数可以是任意精度/大。但有时必须将常量转换为真正的 Go 类型。在你的情况下,一个浮点数和一个整数。并非每个常量都可以转换,这是编译时错误。区别在于:
Big*0.1被转换为浮点数,而Big/10被转换为 int。博文中的详细信息。
标签: go