You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang实现正负奇偶数字分类程序的问题求助

问题修复与实现方案

一、修复if-else版本代码

你的代码只处理了负数的两种情况,完全遗漏了正数的判断逻辑,这就是输入正数时仍输出负数相关信息的原因。修正后的代码需要覆盖所有四类情况:

package main

import (
    "fmt"
)

func main() {
    var num int
    fmt.Scanln(&num)
    
    if num < 0 {
        if num%2 == 0 {
            fmt.Println("The number is negative and even")
        } else {
            fmt.Println("The number is negative and odd")
        }
    } else if num > 0 {
        if num%2 == 0 {
            fmt.Println("The number is positive and even")
        } else {
            fmt.Println("The number is positive and odd")
        }
    } else {
        fmt.Println("The number is zero") // 额外补充0的处理,需求未提及但属于合理边界场景
    }
}

也可以用组合条件的方式写,逻辑更紧凑:

package main

import (
    "fmt"
)

func main() {
    var num int
    fmt.Scanln(&num)
    
    if num < 0 && num%2 == 0 {
        fmt.Println("The number is negative and even")
    } else if num < 0 && num%2 != 0 {
        fmt.Println("The number is negative and odd")
    } else if num > 0 && num%2 == 0 {
        fmt.Println("The number is positive and even")
    } else if num > 0 && num%2 != 0 {
        fmt.Println("The number is positive and odd")
    } else {
        fmt.Println("The number is zero")
    }
}

二、用switch语句实现

Go的switch支持基于条件表达式的判断,非常适合这类场景。通过switch true可以直接匹配不同的条件分支:

package main

import (
    "fmt"
)

func main() {
    var num int
    fmt.Scanln(&num)
    
    switch true {
    case num < 0 && num%2 == 0:
        fmt.Println("The number is negative and even")
    case num < 0 && num%2 != 0:
        fmt.Println("The number is negative and odd")
    case num > 0 && num%2 == 0:
        fmt.Println("The number is positive and even")
    case num > 0 && num%2 != 0:
        fmt.Println("The number is positive and odd")
    default:
        fmt.Println("The number is zero")
    }
}

内容的提问来源于stack exchange,提问作者Belevcek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:13:15