为什么在 Go 中将 float64 转换为 int32 会给出负数?



偶尔,我们在 Golang 中错误地将float64直接投射到int32

raw = 529538871408
fv = float64(raw)
fmt.Println(raw)
fmt.Println(fv)
fmt.Println(int32(fv))

输出

529538871408
5.29538871408e+11
-2147483648       

为什么int32(fv)给出负数?

众所周知,C++ 中的long和 Golang 中的float64都是 64 位 IEEE 754 双精度。所以我们在C++中尝试相同的代码

int64_t iv = 529538871408;
std::cout << iv << std::endl;
double fv = double(iv);
std::cout << fv << std::endl;
int32_t i32v = int32_t(fv);
std::cout << i32v << std::endl;

输出:

529538871408
5.29539e+11
2147483647

结果是2147483647,为什么?我错过了什么吗?还是出了什么问题?

在 go 中,你可以溢出到符号位

package main
import (
"fmt"
)
func main() {
a, b := int32(2147483647), int32(1)
c := a + b
fmt.Printf("%d %T", c, c)
}

在操场上看看

最新更新