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条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法