使用 For 循环编写一个 Go 程序,打印数组中奇数索引位置的元素(不是实际的奇数位置)。在此,for 循环 (for i := 1; i < len(odarray); i += 2) 从一开始迭代,每次递增 2,直到数组长度。在循环中,我们打印所有位于奇数索引位置的数组元素。
package main
import "fmt"
func main() {
odarray := []int{11, 12, 32, 45, 65, 90, 70, 80}
fmt.Println("The List of Array Items in Odd Index Position = ")
for i := 1; i < len(odarray); i += 2 {
fmt.Println(odarray[i])
}
}
The List of Array Items in Odd Index Position =
12
45
90
80
Golang 使用 For Loop range 打印数组奇数索引位置元素的程序
我们使用了一个额外的 if 语句 (if i%2 != 0) 来检查索引位置是否不能被 2 整除,这意味着它是一个奇数索引位置。接下来,打印该数字。
package main
import "fmt"
func main() {
odarray := []int{11, 12, 32, 45, 65, 90, 70, 80}
fmt.Println("The List of Array Items in Odd Index Position = ")
for i, _ := range odarray {
if i%2 != 0 {
fmt.Println(odarray[i])
}
}
}
The List of Array Items in Odd Index Position =
12
45
90
80
此 Golang 程序允许用户输入数组大小和元素,然后打印奇数索引位置的元素。
package main
import "fmt"
func main() {
var size int
fmt.Print("Enter the Even Odd Array Size = ")
fmt.Scan(&size)
odarray := make([]int, size)
fmt.Print("Enter the Even Odd Array Items = ")
for i := 0; i < size; i++ {
fmt.Scan(&odarray[i])
}
fmt.Println("The List of Array Items in Odd index Position = ")
for i := 1; i < len(odarray); i += 2 {
fmt.Println(odarray[i])
}
}
