Files
go-basics/stage02-control-flow/02-switch/main.go
T

135 lines
2.5 KiB
Go
Raw Normal View History

2026-03-13 23:54:07 +08:00
package main
import "fmt"
func exercise1() {
fmt.Println("=== 练习1:基本switch ===")
day := 3
// 使用switch语句,根据day的值输出对应的星期
// 1: 星期一, 2: 星期二, 3: 星期三, 4: 星期四
// 5: 星期五, 6: 星期六, 7: 星期日
// 其他: 无效的天数
switch ____ {
case ____:
fmt.Println("星期一")
case ____:
fmt.Println("星期二")
case ____:
fmt.Println("星期三")
case ____:
fmt.Println("星期四")
case ____:
fmt.Println("星期五")
case ____:
fmt.Println("星期六")
case ____:
fmt.Println("星期日")
default:
fmt.Println("无效的天数")
}
}
func exercise2() {
fmt.Println("\n=== 练习2:多值匹配 ===")
month := 1
// 使用switch语句,根据month的值输出季节
// 使用多值匹配(一个case匹配多个值)
// 3,4,5: 春季
// 6,7,8: 夏季
// 9,10,11: 秋季
// 12,1,2: 冬季
switch ____ {
case ____, ____, ____:
fmt.Println("春季")
case ____, ____, ____:
fmt.Println("夏季")
case ____, ____, ____:
fmt.Println("秋季")
case ____, ____, ____:
fmt.Println("冬季")
default:
fmt.Println("无效的月份")
}
}
func exercise3() {
fmt.Println("\n=== 练习3:无表达式的switch ===")
score := 92
// 使用无表达式的switch,根据score判断等级
// 90-100: 优秀
// 80-89: 良好
// 60-79: 及格
// 0-59: 不及格
switch {
case ____:
fmt.Printf("分数: %d, 等级: 优秀\n", score)
case ____:
fmt.Printf("分数: %d, 等级: 良好\n", score)
case ____:
fmt.Printf("分数: %d, 等级: 及格\n", score)
case ____:
fmt.Printf("分数: %d, 等级: 不及格\n", score)
}
}
func exercise4() {
fmt.Println("\n=== 练习4:fallthrough ===")
num := 1
// 使用switch和fallthrough,当num=1时:
// 输出"one"然后继续执行case 2输出"two"
// 提示:在case 1的末尾添加fallthrough
switch ____ {
case 1:
fmt.Println("one")
____
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}
func exercise5() string {
fmt.Println("\n=== 练习5:switch返回值 ===")
status := 200
// 使用switch语句,根据HTTP状态码返回对应的描述
// 200: OK
// 404: Not Found
// 500: Internal Server Error
// 其他: Unknown Status
var result string
switch ____ {
case 200:
result = "OK"
case 404:
result = "Not Found"
case 500:
result = "Internal Server Error"
default:
result = "Unknown Status"
}
return result
}
func main() {
fmt.Println("=== switch 练习 ===\n")
exercise1()
exercise2()
exercise3()
exercise4()
result := exercise5()
fmt.Println(result)
}