在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
14.数组数组定义以及初始化
len(a)返回数组的长度 带索引的数组遍历 1: var index, val int
2: for index, val := range a {
3: } 另一种遍历 1: var a [5]int = [5]int {1, 3, 5, 8, 7} 2: func main() { 3: sum := 0 4: for _, val := range a { 5: sum += val 6: } 7: fmt.Println(sum) 8: } 二维数组 1: for i, val := range a{ 2: for j,val_2 := range val { 3: //
4: } 5: } 数组拷贝和传参 1: var a [3]int 2: a[0] = 10 3: a[1] = 20 4: a[2] = 30 1: func main(){ 2: b:=a 3: b[0]= 1000 4: fmt.Println(a, b) 5: } 6: >>> [1000 20 30] [1000 20 30] 7: // 可以看出来这里是类似python里的深拷贝
另外一种 1: func main() { 2: var a []int = []int{10, 20, 30} 3: modify(a) 4: fmt.Println(a, b) 5: } 6: func modify(b []int) { 7: b[0] = 1000 8: return
9: } 结果 1: >>> [1000 20 30] 练习: 1: var a [3]int = [3]int{10, 20, 30} 2: func main() { 3: sum := 0 4: for i:=0; i<len(a);i++ { 5: sum += a[i] 6: } 7: fmt.Println(sum) 8: } 2.找出数组中和为给定值的两个元素的下标,比如数组:[1,3,5,8,7],找出两个元素之和等于8的下标分别是(0, 4)和(1, 2) 常规写法: 1: var a [5]int = [5]int {1, 3, 5, 8, 7} 2: func main() { 3: for i:=0; i<len(a); i++ { 4: for j:=i+1; j<len(a)-i; j++{ 5: if a[i]+a[j] == 8 {
6: fmt.Println(i, j) 7: } 8: } 9: } 10: } |
请发表评论