Go入门 - 计算平均数

《学习Go语言》

编写一个函数用于计算一个float64类型的slice的平均数

package main
import "fmt"
func main() {
	xs := []float64{1,2,3,4,5,6,7}
	avg := average(xs)
	fmt.Printf("The average is %f", avg)
}

func average(xs []float64) (avg float64) {
	sum := 0.0
	switch len(xs) {
		case 0:
			avg = 0
		default:
			for _,v := range xs {
				sum += v
			}
			avg = sum / float64(len(xs))
	}
	return
}

打印结果

The average is 4.000000

你可能感兴趣的:(Go)