这个 Go 程序通过 for 循环迭代 1 到 n 来查找从 1 到 n 的奇数之和。在循环中,if 语句过滤奇数并将总和添加到奇数总和中。
package main
import "fmt"
func main() {
var oddnum, Oddtotal int
fmt.Print("Enter the Number to find Odd Sum = ")
fmt.Scanln(&oddnum)
Oddtotal = 0
fmt.Println("List of Odd Numbers from 1 to ", oddnum, " are = ")
for x := 1; x <= oddnum; x++ {
if x%2 != 0 {
fmt.Print(x, "\t")
Oddtotal = Oddtotal + x
}
}
fmt.Println("\nSum of Odd Numbers from 1 to ", oddnum, " = ", Oddtotal)
}
Enter the Number to find Odd Sum = 10
List of Odd Numbers from 1 to 10 are =
1 3 5 7 9
Sum of Odd Numbers from 1 to 10 = 25
Golang 程序查找奇数之和。
在此程序中,我们修改了 for 循环,使其从 1 开始,并以 2 为增量来计算奇数之和。
package main
import "fmt"
func main() {
var oddnum, Oddtotal int
fmt.Print("Enter the Number to find Odd Sum = ")
fmt.Scanln(&oddnum)
Oddtotal = 0
fmt.Println("List of Odd Numbers from 1 to ", oddnum, " are = ")
for x := 1; x <= oddnum; x = x + 2 {
fmt.Print(x, "\t")
Oddtotal = Oddtotal + x
}
fmt.Println("\nSum of Odd Numbers from 1 to ", oddnum, " = ", Oddtotal)
}
Enter the Number to find Odd Sum = 25
List of Odd Numbers from 1 to 25 are =
1 3 5 7 9 11 13 15 17 19 21 23 25
Sum of Odd Numbers from 1 to 25 = 169
这个 程序 计算从 min 到 max 的奇数之和。在这里,我们使用了一个额外的 if 语句来将用户输入的奇数值(如果有偶数值)加 1 以保持为奇数。
package main
import "fmt"
func main() {
var Oddmin, Oddmax, Oddtotal int
fmt.Print("Enter the Minimum Odd Number = ")
fmt.Scanln(&Oddmin)
fmt.Print("Enter the Maximum Odd Number = ")
fmt.Scanln(&Oddmax)
if Oddmin%2 == 0 {
Oddmin++
}
Oddtotal = 0
fmt.Println("Odd Numbers from ", Oddmin, " to ", Oddmax, " = ")
for x := Oddmin; x <= Oddmax; x = x + 2 {
fmt.Print(x, "\t")
Oddtotal = Oddtotal + x
}
fmt.Println("\nSum of Odd Numbers from ", Oddmin, " to ", Oddmax, " = ", Oddtotal)
}
Enter the Minimum Odd Number = 10
Enter the Maximum Odd Number = 50
Odd Numbers from 11 to 50 =
11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
Sum of Odd Numbers from 11 to 50 = 600
它与第一个奇数之和示例相同。但是,它计算的是最小和最大限制之间的奇数和。
package main
import "fmt"
func main() {
var Oddmin, Oddmax, Oddtotal int
fmt.Print("Enter the Minimum Odd Number = ")
fmt.Scanln(&Oddmin)
fmt.Print("Enter the Maximum Odd Number = ")
fmt.Scanln(&Oddmax)
Oddtotal = 0
fmt.Println("Odd Numbers from ", Oddmin, " to ", Oddmax, " = ")
for x := Oddmin; x <= Oddmax; x++ {
if x%2 != 0 {
fmt.Print(x, "\t")
Oddtotal = Oddtotal + x
}
}
fmt.Println("\nSum of Odd Numbers from ", Oddmin, " to ", Oddmax, " = ", Oddtotal)
}
