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.go240 chars14 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.go25 chars2 lines
gistlibby LogSnag