当我将Math.nan()和Math.maxfloat64施放到INT上时,为什么结果在GO1.14.2和GO1.17.2之间有所不同?

发布于 2025-01-23 19:59:38 字数 687 浏览 2 评论 0 原文

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

我搜索了一个模拟问题:为什么golang的uint64和maxfloat64在golang中等于?,它在不同的硬件环境中说,在不同的硬件环境中,nan.nan.nan.nan ()也许有所不同,但是我在MacOS M1系统中运行了代码,只有Golang版本不同。为什么结果在GO1.14.2和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))
}

That is my test code snippet. When I run the above code use go1.14.2, the result is

-9223372036854775808
-9223372036854775808

but the same code run in go1.17.2, the result is

0
9223372036854775807

I searched the simular question: Why Is uint64 of NaN and MaxFloat64 equal in Golang?, which said that in the different hardware environment, the math.NaN() maybe different, but I run the code both in my MacOS M1 system, just golang version is different. Why the result is different between go1.14.2 and go1.17.2?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

惟欲睡 2025-01-30 19:59:38

在涉及浮点或复杂值的所有非恒定转换中,如果结果类型不能表示转换成功的值,但结果值取决于实现。

您转换浮点数值 nan int int 类型的有效值不包括 nan 值,因此您转换的值不能由类型 int 的值表示因此,结果是依赖于实现。基本上,规格允许其从版本更改为平台到平台。您不能(不应该)假设转换结果的特定 int 值。

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.

You convert the floating-point value NaN to int. The valid values of the int type does not include the NaN value, so the value you convert cannot be represented by a value of type int, so the result is implementation-dependent. Basically, the spec allows it to be changed from version to version, from platform to platform. You cannot (should not) assume a specific int value for the conversion result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文