go - 在将float常量转换为int的类型期间,常量被截断为整数错误

标签 go

以下代码在“ 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:

  1. ...
  2. When converting a floating-point number to an integer, the fraction is discarded (truncation towards zero).
  3. ...


因此这是可能的:
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)表达式,因此是非法的。

阅读有关ConversionsRepresentability的更多信息

关于go - 在将float常量转换为int的类型期间,常量被截断为整数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404065/

相关文章:

go - 在 Go 中交叉编译 pkg 导入

go - 输入 noRows struct{} var _ Result = noRows{}

go - kubernetes golang 客户端示例

go - 如何限制 Golang 中变量的值?

json - Go中接口(interface)的自定义JSON序列化和反序列化

go - go中的包解耦

google-app-engine - 有没有办法以交互方式为 Go GAE 应用程序创建新的数据存储实体类型?

go - 如何在golang中写入已经打开的FD

go - 如何获取 Go 依赖者列表

python - 去替代 python loop.last