在Golang中求和n个切片的值

huangapple go评论86阅读模式
英文:

Sum of "n" Slices values in Golang

问题

我正在尝试使用切片和循环来制作一个简单的平均值计算器,使用的是golang语言。

但是在VS code中出现了一个错误,错误信息如下:

panic: runtime error: index out of range [0] with length 0
goroutine 1 [running]:
main.main()
C:/Desktop/cs50/week2/myarray.go:16 +0x134
exit status 2

我在W10上使用的是VS code。

我的代码如下:

package main

import "fmt"

func main() {
	var n int
	scores := []uint{}
	var sumScores float32 = 0

	fmt.Println("How many scores?") //询问用户有多少个值
	fmt.Scan(&n)                    //获取值的数量

	for i := 0; i < n; i++ {
		fmt.Printf("Scores: ")                     //询问值
		fmt.Scan(&scores[i])                       //获取值
		sumScores = sumScores + float32(scores[i]) //求和
	}

	fmt.Printf("Average: %f\n", sumScores/float32(n)) //平均值
}

有什么想法是什么出错了吗?

我认为可能与使用float32定义切片有关。

提前感谢你的帮助。

英文:

I am trying to make a simple average calculator in golang using Slices and For Loops.

But i am having an error in VS code, this one:

> panic: runtime error: index out of range [0] with length 0
>goroutine 1 [running]:
>main.main()
> C:/Desktop/cs50/week2/myarray.go:16 +0x134
> exit status 2

I am using VS code on W10.

My code:

package main

import &quot;fmt&quot;

func main() {
	var n int
	scores := []uint{}
	var sumScores float32 = 0

	fmt.Println(&quot;How many scores?&quot;) //ask user how many values
	fmt.Scan(&amp;n)                    //get how many values

	for i := 0; i &lt; n; i++ {
		fmt.Printf(&quot;Scores: &quot;)                     // ask for values
		fmt.Scan(&amp;scores[i])                       // get values
		sumScores = sumScores + float32(scores[i]) // sum values
	}

	fmt.Printf(&quot;Average: %f\n&quot;, sumScores/float32(n)) //average value
}

Any idea what can be wrong?

I think it could be related to my Slice definition using float32.

Thank you in advanced.

答案1

得分: 2

这段代码完全正常,你只需要指定切片的初始大小:

func main() {
    var n int
    var sumScores float32 = 0

    fmt.Println("How many scores?") //询问用户有多少个值
    fmt.Scan(&n)                    //获取值的数量
    scores := make([]uint, n, n)

    for i := 0; i < n; i++ {
        fmt.Printf("Scores: ") //询问值
        fmt.Scan(&scores[i])                       //获取值
        sumScores = sumScores + float32(scores[i]) //求和
    }

    fmt.Printf("Average: %f\n", sumScores/float32(n)) //平均值
}

为了学习目的

你声明的scores切片是一个空切片,所以你可以先向其中添加元素,然后在新生成的位置上扫描数字。(但这当然不是解决这个特定问题的方式)

func main() {
    var n int
    scores := []uint{}
    var sumScores float32 = 0

    fmt.Println("How many scores?") //询问用户有多少个值
    fmt.Scan(&n)                    //获取值的数量

    for i := 0; i < n; i++ {
        fmt.Printf("Scores: ") //询问值
        scores = append(scores, 0)
        fmt.Scan(&scores[i])                       //获取值
        sumScores = sumScores + float32(scores[i]) //求和
    }

    fmt.Printf("Average: %f\n", sumScores/float32(n)) //平均值
}
英文:

This works perfectly, you just have to indicate the slice`s inital size:

func main() {
	var n int
	var sumScores float32 = 0

	fmt.Println(&quot;How many scores?&quot;) //ask user how many values
	fmt.Scan(&amp;n)                    //get how many values
	scores := make([]uint, n, n)

	for i := 0; i &lt; n; i++ {
		fmt.Printf(&quot;Scores: &quot;) // ask for values

		fmt.Scan(&amp;scores[i])                       // get values
		sumScores = sumScores + float32(scores[i]) // sum values
	}

	fmt.Printf(&quot;Average: %f\n&quot;, sumScores/float32(n)) //average value
}

for the learning purposes

The way you've declared the scores slice, it's just an empty slice so you can append to it first and then scan the number in newly generated position. (but this is certainly not the way for this specific problem)

func main() {
	var n int
	scores := []uint{}
	var sumScores float32 = 0

	fmt.Println(&quot;How many scores?&quot;) //ask user how many values
	fmt.Scan(&amp;n)                    //get how many values

	for i := 0; i &lt; n; i++ {
		fmt.Printf(&quot;Scores: &quot;) // ask for values
		scores = append(scores, 0)
		fmt.Scan(&amp;scores[i])                       // get values
		sumScores = sumScores + float32(scores[i]) // sum values
	}

	fmt.Printf(&quot;Average: %f\n&quot;, sumScores/float32(n)) //average value
}

答案2

得分: 0

> scores := []uint{}

这是一个切片字面量,你应该使用Golang内置的append函数。

就像@no0ob的第二个示例一样,或者这样:

func main() {
    var n int
    var tmpVal uint
    scores := []uint{}
    var sumScores float32 = 0

    fmt.Println("有多少个分数?") //询问用户有多少个值
    fmt.Scan(&n)                    //获取值的数量

    for i := 0; i < n; i++ {
        fmt.Printf("分数:") // 询问值
        fmt.Scan(&tmpVal) // 将输入保存到tmpVal
        scores = append(scores, tmpVal) // 将tmpVal追加到scores中
        sumScores = sumScores + float32(scores[i]) // 求和
    }

    fmt.Printf("平均值:%f\n", sumScores/float32(n)) //平均值
}
英文:

> scores := []uint{}

This is a slice literal, you should use Golang built-in function append with it.

Like @no0ob's second example does, or this:

func main() {
    var n int
    var tmpVal uint
    scores := []uint{}
    var sumScores float32 = 0

    fmt.Println(&quot;How many scores?&quot;) //ask user how many values
    fmt.Scan(&amp;n)                    //get how many values

    for i := 0; i &lt; n; i++ {
        fmt.Printf(&quot;Scores: &quot;) // ask for values
        fmt.Scan(&amp;tmpVal) // save input to tmpVal
        scores = append(scores, tmpVal) // append tmpVal to scores
        sumScores = sumScores + float32(scores[i]) // sum values
    }

    fmt.Printf(&quot;Average: %f\n&quot;, sumScores/float32(n)) //average value
}

huangapple
  • 本文由 发表于 2022年6月2日 06:32:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/72468706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定