Golang 如何使用数组计算平均值

Golang 如何使用数组计算平均值

给定一个n元素的数组,你的任务是找出数组的平均值。

方法:

  • 接受数组的大小。
  • 接受数组的元素。
  • 使用for循环将元素的和存储下来。
  • 计算平均值 = (元素的和/数组的大小)
  • 输出平均值。

示例:

输入:

n = 4
array = 1, 2, 3, 4

输出:

sum = 10
average = 2.5

// Golang program to calculate the average of numbers in array
package main

import "fmt"

func main() {

    // declaring an array of values
    array := []int{1, 2, 3, 4}

    // size of the array
    n := 4

    // declaring a variable to store the sum
    sum := 0

    // traversing through the array using for loop
    for i := 0; i < n; i++ {

        // adding the values of array to the variable sum
        sum += (array[i])
    }

    // declaring a variable avg to find the average
    avg := (float64(sum)) / (float64(n))

    // typecast all values to float
    // to get the correct result
    fmt.Println("Sum = ", sum, "\nAverage = ", avg)
} 

输出

Sum =  10 
Average =  2.5

这里, n 是数组的大小, sum 是存储数组所有值的和的变量。使用for循环我们可以得到数组元素的和。计算和后,我们 必须将sum和数组的大小的数据类型转换为float ,这样我们不会丢失任何小数值。
要了解更多方法,你可以查看文章Program for the average of an array (Iterative and Recursive)。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程