In Go, you can easily compute the average of a list of numbers using a straightforward approach that sums up the values and divides them by the total count. Calculating the average of a list is a fundamental operation in data analysis and statistics.
You can see here how to find the sum of a list in Go.
The following code calculates the average of a list of numbers:
package mainimport ("fmt")func calculateAverage(list []float64) float64 {total := 0.0for _, num := range list {total += num}return total / float64(len(list))}func main() {numbers := []float64{3.2, 5.8, 2.1, 9.7, 4.5}avg := calculateAverage(numbers)fmt.Printf("Average: %.2f\n", avg)}
The calculateAverage
function takes a slice of float64
values as input and uses a loop to accumulate the sum of all elements. By iterating through the list and adding each element to the total
variable, the function finds the total sum of the array. The average is then computed by dividing the total sum by the count of elements in the list.
The algorithm's efficiency in terms of time and space is as follows:
Time complexity: The time complexity of this algorithm is
Space complexity: The space complexity of the algorithm is
Free Resources