Sum of "n" Slices values in Golang

Issue

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.

Solution

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

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

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

    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
}

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("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
        scores = append(scores, 0)
        fmt.Scan(&scores[i])                       // get values
        sumScores = sumScores + float32(scores[i]) // sum values
    }

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

Answered By – no0ob

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.