编写一个 Go 程序,使用 For 循环在数组中打印负数。在这里,我们使用 for 循环 (for i = 0; i < ngsize; i++) 来迭代用户输入的数组项。在循环中,if 条件 (if negArr[i] < 0) 检查数字是否小于零。如果为 True,则表示它是负数,将其打印出来。
package main
import "fmt"
func main() {
var ngsize, i int
fmt.Print("Enter the Negative Array Size = ")
fmt.Scan(&ngsize)
negArr := make([]int, ngsize)
fmt.Print("Enter the Negative Array Items = ")
for i = 0; i < ngsize; i++ {
fmt.Scan(&negArr[i])
}
fmt.Print("\nThe Negative Numbers in this negArr = ")
for i = 0; i < ngsize; i++ {
if negArr[i] < 0 {
fmt.Print(negArr[i], " ")
}
}
fmt.Println()
}
Enter the Negative Array Size = 5
Enter the Negative Array Items = 22 -9 11 -8 -15
The Negative Numbers in this negArr = -9 -8 -15
Go 语言使用 For Loop Range 打印数组中的负数程序
package main
import "fmt"
func main() {
var ngsize, i int
fmt.Print("Enter the Negative Array Size = ")
fmt.Scan(&ngsize)
negArr := make([]int, ngsize)
fmt.Print("Enter the Negative Array Items = ")
for i = 0; i < ngsize; i++ {
fmt.Scan(&negArr[i])
}
fmt.Print("\nThe Negative Numbers in this negArr = ")
for _, ng := range negArr {
if ng < 0 {
fmt.Print(ng, " ")
}
}
fmt.Println()
}
Enter the Negative Array Size = 7
Enter the Negative Array Items = 0 22 -90 -11 3 -2 2
The Negative Numbers in this negArr = -90 -11 -2
在这个 Golang 程序中,我们创建了一个函数 (printNegativeNum(negArr []int)) 来打印给定数组中的负数。
package main
import "fmt"
func printNegativeNum(negArr []int) {
fmt.Print("\nThe Negative Numbers in this negArr = ")
for _, ng := range negArr {
if ng < 0 {
fmt.Print(ng, " ")
}
}
}
func main() {
var ngsize, i int
fmt.Print("Enter the Negative Array Size = ")
fmt.Scan(&ngsize)
negArr := make([]int, ngsize)
fmt.Print("Enter the Negative Array Items = ")
for i = 0; i < ngsize; i++ {
fmt.Scan(&negArr[i])
}
printNegativeNum(negArr)
fmt.Println()
}
Enter the Negative Array Size = 5
Enter the Negative Array Items = 11 -99 -66 0 -33
The Negative Numbers in this negArr = -99 -66 -33