package main
import (
"fmt"
)
func main() {
var n [10]int //声明数组
var i, j int
// var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0} //定义并初始化
// var balance2 = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}
for i = 0; i < 10; i++ { //数组初始化
n[i] = i + 100
}
for j = 0; j < 10; j++ {
fmt.Printf("Element[%d] = %d\n", j, n[j])
}
// 多维数组
var a = [3][2]int{
{0, 0},
{1, 2},
{2, 4}, //只想说这里为什么非要加逗号,反人类的逗号,但是美观一点
}
var n1, n2 int
for n1 = 0; n1 < 3; n1++ {
for n2 = 0; n2 < 2; n2++ {
fmt.Printf("a[%d][%d] = %d\n", n1, n2, a[n1][n2])
}
}
//数组函数
var balance = []int{1000, 2, 3, 17, 50}
var avg float32
avg = getAverage(balance, 5)
fmt.Printf("平均值为: %f ", avg)
}
//传数组给函数
func getAverage(arr []int, size int) float32 { //这个数组没有没有设定个数,也可以设定个数
var i int
var avg, sum float32
for i = 0; i < size; i++ {
sum += float32(arr[i])
}
//这里必须要有类型转换否则会出现 invalid operation: sum / size (mismatched types float32 and int)
avg = sum / float32(size)
return avg
}