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
相关产品推荐
相关产品推荐

