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 "fmt"
func main() {
var n int
scores := []uint{}
var sumScores float32 = 0
fmt.Println("How many scores?") //ask user how many values
fmt.Scan(&n) //get how many values
for i := 0; i < n; i++ {
fmt.Printf("Scores: ") // ask for values
fmt.Scan(&scores[i]) // get values
sumScores = sumScores + float32(scores[i]) // sum values
}
fmt.Printf("Average: %f\n", 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.
scores
slice is of length 0. You don't actually use that slice. You can simply scan to an int, and keep adding that to sumScores.scores = make([]uint, n)