此 Go 程序中从 1 到 n 打印奇数的 for 循环从一开始,在 oddnum 处停止。在循环内部,if 条件 (x % 2 != 0) 检查数字除以二的余数是否不等于零。如果为真,则打印该奇数。
package main
import "fmt"
func main() {
var odnum int
fmt.Print("Enter the Number to Print Odd's = ")
fmt.Scanln(&odnum)
for x := 1; x <= odnum; x++ {
if x%2 != 0 {
fmt.Print(x, "\t")
}
}
}
Enter the Number to Print Odd's = 10
1 3 5 7 9
Golang 程序打印从 1 到 N 的奇数
在此 Golang 程序中,for 循环从一开始,每次增加二 (x = x + 2)。这表明所有数字都将是奇数,无需添加额外的 if 条件来检查余数。
package main
import "fmt"
func main() {
var odnum int
fmt.Print("Enter the Number to Print Odd's = ")
fmt.Scanln(&odnum)
for x := 1; x <= odnum; x = x + 2 {
fmt.Print(x, "\t")
}
}
Enter the Number to Print Odd's = 20
1 3 5 7 9 11 13 15 17 19
此 Go 程序显示从最小值到最大值的奇数。第一个 if 语句 (Oddmin % 2 == 0) 检查最小值是否为偶数,如果为真,则最小值增加一 (oddmin++) 以变为奇数。在 for 循环中,我们将 odd 值增加了二,以便所有数字都是奇数。
package main
import "fmt"
func main() {
var oddmin, oddmax int
fmt.Print("Enter the Minimum to Start Printing Odd's = ")
fmt.Scanln(&oddmin)
fmt.Print("Enter the Maximum to End Printing Odd's = ")
fmt.Scanln(&oddmax)
if oddmin%2 == 0 {
oddmin++
}
fmt.Print("The Odd Numbers from ", oddmin, " to ", oddmax, " are \n")
for i := oddmin; i <= oddmax; i = i + 2 {
fmt.Print(i, "\t")
}
}
Enter the Minimum to Start Printing Odd's = 10
Enter the Maximum to End Printing Odd's = 30
The Odd Numbers from 11 to 30 are
11 13 15 17 19 21 23 25 27 29
这个 Golang 奇数 示例 与第一个示例相同。但是,它打印从最小值开始并在最大限制处结束的奇数。
package main
import "fmt"
func main() {
var oddmin, oddmax int
fmt.Print("Enter the Minimum to Start Printing Odd's = ")
fmt.Scanln(&oddmin)
fmt.Print("Enter the Maximum to End Printing Odd's = ")
fmt.Scanln(&oddmax)
fmt.Print("The Odd Numbers from ", oddmin, " to ", oddmax, " are \n")
for i := oddmin; i <= oddmax; i++ {
if i%2 != 0 {
fmt.Print(i, "\t")
}
}
}
