find the average of a list of numbers in go

To find the average of a list of numbers in Go, we can use arrays or slices to store the numbers and then use the math package to perform the necessary mathematical operations.

Here is an example using slices:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    // Declare a slice of numbers
    numbers := []float64{1.0, 2.0, 3.0, 4.0, 5.0}

    // Calculate the sum of the numbers
    var sum float64
    for _, num := range numbers {
        sum += num
    }

    // Calculate the average of the numbers
    average := sum / float64(len(numbers))

    // Print the average
    fmt.Printf("The average is %.2f\n", average)
}
430 chars
24 lines

In this example, we declare a float64 slice called numbers, containing 5 numbers. We then loop through the slice and add each number to the sum variable. After the loop, we calculate the average by dividing the sum by the length of the slice, converted to float64. Finally, we print the average using fmt.Printf, with a precision of 2 decimal places.

This program will output:

main.go
The average is 3.00
20 chars
2 lines

related categories

gistlibby LogSnag