以下代码在“ var a int = int(1.333)”行上引发错误“常量被截断为整数”。我是GO的新手,无法弄清实际问题。
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
const k float64=2.2
var a int = int(1.333)
var f float64 = math.Sqrt(float64(x*x+y*y))
var z uint = uint(f)
fmt.Println(x, y, z,a)
}
最佳答案
常数的转换与非常数的转换遵循不同的规则。
第一个非常数:
Conversions between numeric types
For the conversion of non-constant numeric values, the following rules apply:
- ...
- When converting a floating-point number to an integer, the fraction is discarded (truncation towards zero).
- ...
因此这是可能的:
var f = float64(1.333)
var i = int(f)
现在常量:
A constant value x can be converted to type T if x is representable by a value of T.
然后,在文档中,有一个示例表达式列表,其中一个是这样的:
int(1.2) // illegal: 1.2 cannot be represented as an int
关于代表性
A constant x is representable by a value of type T if one of the following conditions applies:
- x is in the set of values determined by T.
- T is a floating-point type and x can be rounded to T's precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE negative zero further simplified to an unsigned zero. Note that constant values never result in an IEEE negative zero, NaN, or infinity.
- T is a complex type, and x's components real(x) and imag(x) are representable by values of T's component type (float32 or float64).
这3个条件均不适用于
var a int = int(1.333)
表达式,因此是非法的。阅读有关Conversions和Representability的更多信息
关于go - 在将float常量转换为int的类型期间,常量被截断为整数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404065/