当我将 math.NaN() 和 math.MaxFloat64 转换为 int 时,为什么 go1.14.2 和 go1.17.2 的结果不同?

When I cast math.NaN() and math.MaxFloat64 to int, Why the result is different between go1.14.2 and go1.17.2?

package main

import (
    "fmt"
    "math"
)

func main() {
    x, y := math.NaN(), math.MaxFloat64
    fmt.Printf("%d\n", int(x))
    fmt.Printf("%d\n", int(y))
}

这是我的测试代码片段。当我运行上面的代码使用go1.14.2时,结果是

-9223372036854775808
-9223372036854775808

但是在go1.17.2中同样的代码运行,结果是

0
9223372036854775807

我搜索了类似的问题:,它说在不同的硬件环境下,math.NaN() 可能不同,但我 运行 代码都在我的 MacOS M1系统,只是golang版本不同。为什么go1.14.2和go1.17.2的结果不一样?

Spec: Conversions:

In all non-constant conversions involving floating-point or complex values, if the result type cannot represent the value the conversion succeeds but the result value is implementation-dependent.

您将 floating-point 值 NaN 转换为 intint类型的有效值不包括NaN值,所以你转换的值不能用int类型的值表示,所以结果是implementation-dependent .基本上,规范允许它从一个版本到另一个版本、从一个平台到另一个平台进行更改。您不能(不应该)为转换结果假定特定的 int 值。