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.go430 chars24 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.go20 chars2 lines
gistlibby LogSnag