偶尔,我们投float64
至int32
在Golang中直接错误
raw = 529538871408
fv = float64(raw)
fmt.Println(raw)
fmt.Println(fv)
fmt.Println(int32(fv))
输出
529538871408
5.29538871408e+11
-2147483648
为什么
int32(fv)
给定一个负数?众所周知,
long
在 C++ 和 float64
中在 Golang 中是 64 位 IEEE 754 double 。所以我们在 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)
}
check it out on playground
关于c++ - 为什么将 float64 转换为 int32 在 Go 中会给出负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62337886/