Go 程序查找奇偶数之和

这个Go程序通过If else语句判断奇偶性,来计算从1到n的奇偶数之和。for循环帮助GC在1到n之间迭代。如果条件为True,则将数字加到偶数总数中。否则,它会加到奇数总数中。

package main

import "fmt"

func main() {

    var eonum, eventotal, oddtotal int

    fmt.Print("Enter the Number to find Even and Odd Sum = ")
    fmt.Scanln(&eonum)

    eventotal = 0
    oddtotal = 0

    for x := 1; x <= eonum; x++ {
        if x%2 == 0 {
            eventotal = eventotal + x
        } else {
            oddtotal = oddtotal + x
        }
    }
    fmt.Println("\nSum of Even Numbers from 1 to ", eonum, " = ", eventotal)
    fmt.Println("\nSum of Odd Numbers from 1 to ", eonum, "  = ", oddtotal)
}
Go Program to find Sum of Even and Odd

Golang程序查找奇偶数之和。

此Golang程序接受最小值和最大值,并计算最小和最大范围内的奇偶数之和。

package main

import "fmt"

func main() {

    var minnum, maxnum, eventotal, oddtotal, x int

    fmt.Print("Enter the Minimum Number to find Even and Odd Sum = ")
    fmt.Scanln(&minnum)

    fmt.Print("Enter the Maximum Number to find Even and Odd Sum = ")
    fmt.Scanln(&maxnum)

    eventotal = 0
    oddtotal = 0

    for x <= maxnum {
        if x%2 == 0 {
            eventotal = eventotal + x
        } else {
            oddtotal = oddtotal + x
        }
        x++
    }
    fmt.Println("\nSum of Even Numbers = ", eventotal)
    fmt.Println("Sum of Odd Numbers  = ", oddtotal)
}
Enter the Minimum Number to find Even and Odd Sum = 20
Enter the Maximum Number to find Even and Odd Sum = 50

Sum of Even Numbers =  650
Sum of Odd Numbers  =  625

Go 程序使用函数计算奇偶数之和。在这里,我们声明了一个返回奇偶数之和的函数。

package main

import "fmt"

func evenOddSum(minnum int, maxnum int) (int, int) {
    var x, eventotal, oddtotal int
    eventotal = 0
    oddtotal = 0
    for x = minnum; x <= maxnum; x++ {
        if x%2 == 0 {
            eventotal = eventotal + x
        } else {
            oddtotal = oddtotal + x
        }
    }
    return eventotal, oddtotal
}
func main() {

    var minnum, maxnum, eventotal, oddtotal int

    fmt.Print("Enter the Minimum Number to find Even and Odd Sum = ")
    fmt.Scanln(&minnum)

    fmt.Print("Enter the Maximum Number to find Even and Odd Sum = ")
    fmt.Scanln(&maxnum)

    eventotal, oddtotal = evenOddSum(minnum, maxnum)

    fmt.Println("\nSum of Even Numbers = ", eventotal)
    fmt.Println("Sum of Odd Numbers  = ", oddtotal)
}
Enter the Minimum Number to find Even and Odd Sum = 10
Enter the Maximum Number to find Even and Odd Sum = 70

Sum of Even Numbers =  1240
Sum of Odd Numbers  =  1200