dozrhldy285751 2014-02-04 16:52
浏览 18
已采纳

在go中处理数组,由于类型不匹配而无法编译代码

So I'm trying to compile the forllowing code in go, which I just picked up a few hours ago

package main

import "fmt"

func main() {

    a := [...]float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sum := avg(a)
    fmt.Println(sum)

}

func avg(arr []float64) (sum float64) {
    for _, v := range arr {
        sum += v
    }
    sum = sum / float64(len(arr))
    return
}

I get an error saying that I can't pass the 10 element long array because the function was defined with a []float64 array. Is there a way around this or am I missing something obvious?

  • 写回答

3条回答 默认 最新

  • 普通网友 2014-02-04 16:58
    关注

    You define a as array of length and in avg you expect a slice of float64

    If you dont need fixed length define a as slice:

    a := []float64{...}
    

    Or you can convert array to slice:

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改