我最近在试验 golang 的类型系统,遇到了一个与 float 有关的有趣(或不有趣)的行为:
package main
import (
"fmt"
)
func main() {
doesntWork()
works()
}
func doesntWork() {
x := 1234
y := x / 100000.0
s := fmt.Sprintf("%.8f", y)
fmt.Printf("%s\n", s)
}
func works() {
x := 1234
y := float64(x) / 100000.0
s := fmt.Sprintf("%.8f", y)
fmt.Printf("%s\n", s)
}
我认为在上面的例子中,在程序doesntWork()
中,golang 在划分 时不会自动“假定”
通过隐式 float32/64
>intfloat
?那是对的吗?谁能给我指点一些文档或规范,让我可以更多地了解 golang 在上述情况下的行为方式?
最佳答案
这里 10000.0
不是 float64/32,它是一个数字常量。在这种情况下,Go 将为表达式假定 x
的类型,并截断
常量 100000.0 为整数
func doesntWork() {
x := 1234
y := x / 100000.0
s := fmt.Sprintf("%.8f", y)
fmt.Printf("%s\n", s)
}
如果你更新到
func doesntWork() {
x := 1234
y := x / float64(100000.0)
s := fmt.Sprintf("%.8f", y)
fmt.Printf("%s\n", s)
}
它会错误的说
invalid operation: x / float64(100000) (mismatched types int and float64)
同样,如果您将常量更改为 100000.111,其中 截断
为整数将不再给出相同的值,它会出错
func doesntWork() {
x := 1234
y := x / 100000.1
s := fmt.Sprintf("%.8f", y)
fmt.Printf("%s\n", s)
}
会报错
constant 100000 truncated to integer
关于Golang 的类型系统行为——将一个 int 除以一个隐式 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422777/