Finish: 02-switch - switch语句

This commit is contained in:
2026-03-14 20:47:33 +08:00
parent 4838dc107a
commit 50306fbe17
+23 -23
View File
@@ -11,20 +11,20 @@ func exercise1() {
// 1: 星期一, 2: 星期二, 3: 星期三, 4: 星期四
// 5: 星期五, 6: 星期六, 7: 星期日
// 其他: 无效的天数
switch ____ {
case ____:
switch day {
case 1:
fmt.Println("星期一")
case ____:
case 2:
fmt.Println("星期二")
case ____:
case 3:
fmt.Println("星期三")
case ____:
case 4:
fmt.Println("星期四")
case ____:
case 5:
fmt.Println("星期五")
case ____:
case 6:
fmt.Println("星期六")
case ____:
case 7:
fmt.Println("星期日")
default:
fmt.Println("无效的天数")
@@ -34,7 +34,7 @@ func exercise1() {
func exercise2() {
fmt.Println("\n=== 练习2:多值匹配 ===")
month := 1
month := 3
// 使用switch语句,根据month的值输出季节
// 使用多值匹配(一个case匹配多个值)
@@ -42,14 +42,14 @@ func exercise2() {
// 6,7,8: 夏季
// 9,10,11: 秋季
// 12,1,2: 冬季
switch ____ {
case ____, ____, ____:
switch month {
case 3, 4, 5:
fmt.Println("春季")
case ____, ____, ____:
case 6, 7, 8:
fmt.Println("夏季")
case ____, ____, ____:
case 9, 10, 11:
fmt.Println("秋季")
case ____, ____, ____:
case 12, 1, 2:
fmt.Println("冬季")
default:
fmt.Println("无效的月份")
@@ -67,13 +67,13 @@ func exercise3() {
// 60-79: 及格
// 0-59: 不及格
switch {
case ____:
case score >= 90 && score <= 100:
fmt.Printf("分数: %d, 等级: 优秀\n", score)
case ____:
case score >= 80 && score < 90:
fmt.Printf("分数: %d, 等级: 良好\n", score)
case ____:
case score >= 60 && score < 79:
fmt.Printf("分数: %d, 等级: 及格\n", score)
case ____:
case score < 60:
fmt.Printf("分数: %d, 等级: 不及格\n", score)
}
}
@@ -86,10 +86,10 @@ func exercise4() {
// 使用switch和fallthrough,当num=1时:
// 输出"one"然后继续执行case 2输出"two"
// 提示:在case 1的末尾添加fallthrough
switch ____ {
switch num {
case 1:
fmt.Println("one")
____
fallthrough
case 2:
fmt.Println("two")
case 3:
@@ -98,7 +98,7 @@ func exercise4() {
}
func exercise5() string {
fmt.Println("\n=== 练习5:switch返回值 ===")
fmt.Println("=== 练习5:switch返回值 ===")
status := 200
@@ -108,7 +108,7 @@ func exercise5() string {
// 500: Internal Server Error
// 其他: Unknown Status
var result string
switch ____ {
switch status {
case 200:
result = "OK"
case 404:
@@ -122,7 +122,7 @@ func exercise5() string {
}
func main() {
fmt.Println("=== switch 练习 ===\n")
fmt.Println("=== switch 练习 ===")
exercise1()
exercise2()