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

huangapple go评论66阅读模式
英文:

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

我搜索了类似的问题:https://stackoverflow.com/questions/70425809/why-is-uint64-of-nan-and-maxfloat64-equal-in-golang,其中提到在不同的硬件环境中,math.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: https://stackoverflow.com/questions/70425809/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?

答案1

得分: 1

规范:转换:

> 在涉及浮点数或复数值的所有非常量转换中,如果结果类型无法表示该值,则转换成功,但结果值取决于实现。

你将浮点数值 NaN 转换为 intint 类型的有效值不包括 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.

huangapple
  • 本文由 发表于 2022年4月25日 16:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/71996308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定