【问题标题】:int16 number plus float64 in golanggolang中的int16数字加float64
【发布时间】:2015-05-27 09:35:42
【问题描述】:

我想做一件简单的事:

func (this *ScoreProvider) getScore()(res float64) {
    var score1 int16 = 500
    var score2 int16 = 400
    var score3 int16 = 300
    var score4 int16 = 200
    res = score1 * 0.25 + score2 * 0.25 + score3 * 0.25 + score4 * 0.25

    return
}

但是这样报错:

can not use score1 * 0 + score2 * 0 + score3 * 0 + score4 * 0 (type int16) as type float64 in assignment

我怎样才能做到这一点?

【问题讨论】:

  • 你使用的是什么版本的 go?这会在 go1.4 中产生错误,“常量 0.25 被截断为整数”。 play.golang.org/p/SJmHxgXm9k
  • 这确实报错了,我想知道如何快速做到这一点?

标签: go int typeconverter


【解决方案1】:

Go 不提供隐式数字转换,请参阅此常见问题解答:Why does Go not provide implicit numeric conversion?

这意味着您在进行算术运算时不能混合使用不同的类型。它们必须是同一类型。 Spec:

操作数类型必须是identical,除非操作涉及移位或无类型constants

您的情况有点不同,因为0.25untyped constant,但由于它有小数部分,因此无法转换/解释为int16,因此您会收到编译时错误。来自spec

如果常量值不能表示为相应类型的值,则会出错。

在这种情况下,您有 3 个选项:

  1. 将分数显式转换为float64

    res = float64(score1) * 0.25 + float64(score2) * 0.25 +
        float64(score3) * 0.25 + float64(score4) * 0.25
    
  2. 为您的score 变量使用float64 类型。

    var score1 float64 = 500
    var score2 float64 = 400
    // ...
    
  3. 由于您的算法计算平均值,您可以简单地执行以下操作:

    res = float64(score1 + score2 + score3 + score4) / 4
    

【讨论】:

  • 3 号遇到int16 上溢/下溢问题。
  • @PaulHankin 是的,必须牢记这一点。鉴于示例数字,在这种情况下这不是问题。如果数字足够大以至于添加 4 个会导致溢出,那么int16 无论如何都不是表示分数的错误选择。
【解决方案2】:

您的常量 (0.25) 被截断为整数 (0)。

两种解决方法:

将 score1 等变量转换为 float32:

var score1 int16 = 500
var score2 int16 = 400
var score3 int16 = 300
var score4 int16 = 200
res := float32(score1)*0.25 + float32(score2)*0.25 + float32(score3)*0.25 + float32(score4)*0.25

fmt.Println("Score", res)

或更明智的做法是,不要将它们声明为 int16,而是将它们声明为 float32 开头:

var score1a float32 = 500
var score2a float32 = 400
var score3a float32 = 300
var score4a float32 = 200
res2 := score1a * 0.25 + score2a * 0.25 + score3a * 0.25 + score4a * 0.25

fmt.Println("Result 1", res)
fmt.Println("Result 2", res2)

Go Playground

【讨论】:

    【解决方案3】:

    go 中没有自动类型提升,您需要改为包含显式转换。

    我会这样写你的代码:

    package main
    
    import "fmt"
    
    func getScore() float64 {
        s1, s2, s3, s4 := int16(500), int16(400), int16(300), int16(200)
        return (float64(s1) + float64(s2) + float64(s3) + float64(s4)) * 0.25
    }
    
    func main() {
        fmt.Println(getScore())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 2014-04-15
      • 2018-07-04
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多