dsbm49845 2014-05-14 13:50
浏览 148
已采纳

类型不匹配的float64和int

I'm trying to create random grades and adding them to a test_scores array. Then calculate the average.

This program:

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    i := 0
    var test_scores [5]float64
    for i < len(test_scores) {
        test_scores[i] = rand.Float64()
        i++
    }
    fmt.Println(test_scores)

    var total float64 = 0
    i = 0
    for i < len(test_scores) {
        total += test_scores[i]
        i++
    }
    fmt.Println(total)
    fmt.Println(total / len(test_scores))
}

produces:

main.go:24: invalid operation: total / 5 (mismatched types float64 and int)

This one works fine:

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    i := 0
    var test_scores [5]float64
    for i < len(test_scores) {
        test_scores[i] = rand.Float64()
        i++
    }
    fmt.Println(test_scores)

    var total float64 = 0
    i = 0
    for i < len(test_scores) {
        total += test_scores[i]
        i++
    }
    fmt.Println(total)
    fmt.Println(total / 5)
}

The only difference being that in the final line, I'm using a fixed 5 and on the non-working one, I'm using the len(test_scores) call.

Len returns an integer as well, so what's up?

  • 写回答

3条回答 默认 最新

  • douaipi3965 2014-05-14 15:04
    关注

    When you write 5 directly in the source-code that's called a constant. Same goes for writing true. The only difference is that the former is an untyped constant and the latter a typed constant.

    The difference lies in that there's no ambiguity about what type true should have – it'll always be bool but in the case of 5 that's not so obvious and depends on the context.

    The Go compiler will figure out what type to give the constant on compilation. The details of this are described in Go's language specification.

    Edit:

    I realized that there's a mistake in my answer: true is in fact also untyped according to the spec because it may be utilized anywhere where a type deriving from bool is expected. That means:

    type MyBool bool
    
    func DoNothing(b MyBool) {}
    
    DoNothing(true) // true is coerced to MyBool
    

    The answer is still valid, though. The distinction between typed and untyped constants holds.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么