Go 程序打印数组中的正数

此 Go 程序使用 for 循环来迭代用户输入的数组项,以打印数组中的正数。在 for 循环(for i = 0; i < posize; i++)内,if 条件(if posArr[i] >= 0)检查数字是否大于或等于零。如果为 True,则为正数,因此打印它。

package main

import "fmt"

func main() {
    var posize, i int

    fmt.Print("Enter the Positive Array Size = ")
    fmt.Scan(&posize)

    posArr := make([]int, posize)

    fmt.Print("Enter the Positive Array Items  = ")
    for i = 0; i < posize; i++ {
        fmt.Scan(&posArr[i])
    }

    fmt.Print("\nThe Positive Numbers in this posArra = ")
    for i = 0; i < posize; i++ {
        if posArr[i] >= 0 {
            fmt.Print(posArr[i], " ")
        }
    }
    fmt.Println()
}
Enter the Positive Array Size = 5
Enter the Positive Array Items  = -22 0 -9 14 11

The Positive Numbers in this posArra = 0 14 11 

使用 For Loop Range 的 Go 程序打印数组中的正数

package main

import "fmt"

func main() {
    var posize int

    fmt.Print("Enter the Positive Array Size = ")
    fmt.Scan(&posize)

    posArr := make([]int, posize)

    fmt.Print("Enter the Positive Array Items  = ")
    for i := 0; i < posize; i++ {
        fmt.Scan(&posArr[i])
    }

    fmt.Print("\nThe Positive Numbers in this posArra = ")
    for _, po := range posArr {
        if po >= 0 {
            fmt.Print(po, " ")
        }
    }
    fmt.Println()
}
Go program to Print Positive Numbers in an Array

在此 Golang 程序中,我们创建了一个 (printPositveNum(posArr []int)) 函数来打印正数数组。

package main

import "fmt"

func printPositveNum(posArr []int) {
    fmt.Print("\nThe Positive Numbers in this posArra = ")
    for _, po := range posArr {
        if po >= 0 {
            fmt.Print(po, " ")
        }
    }
}
func main() {
    var posize int

    fmt.Print("Enter the Positive Array Size = ")
    fmt.Scan(&posize)

    posArr := make([]int, posize)

    fmt.Print("Enter the Positive Array Items  = ")
    for i := 0; i < posize; i++ {
        fmt.Scan(&posArr[i])
    }
    printPositveNum(posArr)
    fmt.Println()
}
Enter the Positive Array Size = 10
Enter the Positive Array Items  = 1 0 -99 8 -66 -55 2 125 -67 220

The Positive Numbers in this posArra = 1 0 8 2 125 220