find the average of all elements in an array in go

To find the average of all elements in an array in Go, you first need to calculate the sum of all elements in the array, and then divide the sum by the length of the array.

Here's an example code snippet that demonstrates how to do this:

main.go
package main

import "fmt"

func main() {
    nums := []float64{1.0, 2.0, 3.0, 4.0, 5.0}
    sum := 0.0
    for _, num := range nums {
        sum += num
    }
    avg := sum / float64(len(nums))
    fmt.Printf("The average is: %f", avg)
}
240 chars
14 lines

In this example, we have an array nums of type float64 containing the elements 1.0, 2.0, 3.0, 4.0, and 5.0. We initialize a variable sum to 0.0, and then use a for loop to iterate over all elements in the array, adding each element to the sum variable. We then calculate the average by dividing the sum by the length of the array, which we convert to a float64 using the float64() function.

The output of this program would be:

main.go
The average is: 3.000000
25 chars
2 lines

related categories

gistlibby LogSnag