在这篇博文中,你将学习两个程序来寻找数组/片状数字的平均值。
- 第一个程序是寻找固定数组的平均数
- 第二个程序是通过命令行从用户那里读取输入的数值来计算平均值。
以下是该程序所需的golang功能
检查数组的平均数的程序示例
首先声明数组或整数,并在线分配数值
使用范围形式的for循环对数组进行迭代
使用len函数找出数组的长度
最后用总数除以长度,得到平均数
package main
import "fmt"
func main() {
var numbs = []int{51, 4, 5, 6, 24}
total := 0
for _, number := range numbs {
total = total + number
}
average := total / len(numbs) // len function return array size
fmt.Printf("Average of array %d", average)
}
上述程序的输出
Average of array 18
检查用户控制台输入的数字的平均值的程序示例
在这个程序中,用户通过命令行使用fmt.Scanln函数给出输入的数字。
下面是一个从命令行读取数字并返回其平均值的程序代码
package main
import "fmt"
func main() {
var array [50]int
var total, count int
fmt.Print("How many numbers you want to enter: ")
fmt.Scanln(&count)
for i := 0; i < count; i++ {
fmt.Print("Enter value : ")
fmt.Scanln(&array[i])
total += array[i]
}
average := total / count
fmt.Printf("Average is %d", average)
}
上述程序的输出是
How many numbers you want to enter: 5
Enter value : 1
Enter value : 2
Enter value : 3
Enter value : 4
Enter value : 5
Average is 3