【练习1】数组中的基本操作
package main
import "fmt"
func main(){
var a [5] int
fmt.Println("emp", a)
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
fmt.Println("len:", len(a))
b := [5]int{1,2,3,4,5}
fmt.Println("dcl:", b)
var twoD [2][3]int
for i := 0; i < 2; i++{
for j := 0; j<3; j++{
twoD[i][j] = i + j
}
}
fmt.Println("2d:", twoD)
}
【练习2】求数组中的最大值
package main
import (
"fmt"
)
func main(){
var balance = []int {1000, 2, 3, 17, 50}
var avg float32
avg = getAverage( balance, 5)
fmt.Println(avg)
balance2 := []int{2,3,4,43,5,67,666}
fmt.Println(getMax(balance2))
}
func getAverage(arr []int, size int) float32 {
var i, sum int
var avg float32
for i = 0; i < size; i++ {
sum += arr[i]
}
avg = float32(sum) / float32(size)
return avg;
}
func getMax(arr []int) int {
var i, max int
max = arr[0]
for i = 1; i < len(arr); i++ {
if max < arr[i] {
max = arr[i]
}
}
return max
}
网友评论