Files
go-basics/stage02-control-flow/01-if-else/main.go
T

122 lines
2.6 KiB
Go
Raw Normal View History

2026-03-13 23:54:07 +08:00
package main
import (
"fmt"
"strconv"
"strings"
)
func exercise1() {
fmt.Println("=== 练习1:简单if判断 ===")
age := 18
// 使用if语句,判断age是否大于等于18
// 如果是,输出"你已经成年了"
2026-03-14 20:39:58 +08:00
if age >= 18 {
2026-03-13 23:54:07 +08:00
fmt.Println("你已经成年了")
} else {
fmt.Println("你还未成年")
}
}
func exercise2() {
fmt.Println("\n=== 练习2:if-else if-else链 ===")
score := 85
// 使用if-else if-else链,根据score判断等级
// 90-100: 优秀
// 80-89: 良好
// 60-79: 及格
// 0-59: 不及格
2026-03-14 20:39:58 +08:00
if score >= 90 {
2026-03-13 23:54:07 +08:00
fmt.Printf("分数: %d, 等级: 优秀\n", score)
2026-03-14 20:39:58 +08:00
} else if score >= 80 {
2026-03-13 23:54:07 +08:00
fmt.Printf("分数: %d, 等级: 良好\n", score)
2026-03-14 20:39:58 +08:00
} else if score >= 60 {
2026-03-13 23:54:07 +08:00
fmt.Printf("分数: %d, 等级: 及格\n", score)
} else {
fmt.Printf("分数: %d, 等级: 不及格\n", score)
}
}
func exercise3() string {
fmt.Println("\n=== 练习3:带初始化语句的if ===")
// 使用带初始化语句的if,将字符串"42"转换为整数
// 如果转换成功,返回字符串"转换成功: 转换后的值"
// 如果转换失败,返回字符串"转换失败"
2026-03-14 20:39:58 +08:00
if num, err := strconv.Atoi("42"); err == nil {
2026-03-13 23:54:07 +08:00
return fmt.Sprintf("转换成功: %d", num)
} else {
return "转换失败"
}
}
func exercise4() string {
fmt.Println("\n=== 练习4:复杂条件表达式 ===")
username := "admin"
password := "123456"
isActive := true
// 使用if语句,判断:
// 1. 用户名是"admin"
// 2. 密码是"123456"
// 3. 账户是激活状态
// 三个条件都满足时,返回"登录成功",否则返回"登录失败"
2026-03-14 20:39:58 +08:00
if username == "admin" && password == "123456" && isActive == true {
2026-03-13 23:54:07 +08:00
return "登录成功"
} else {
return "登录失败"
}
}
func exercise5() bool {
fmt.Println("\n=== 练习5:逻辑非和或运算 ===")
hasPermission := false
isAdmin := true
// 使用if语句,判断"没有权限但可以是管理员"的情况
// 提示:使用 ! 或 ||
2026-03-14 20:39:58 +08:00
if hasPermission || isAdmin {
2026-03-13 23:54:07 +08:00
return true
}
return false
}
func exercise6() string {
fmt.Println("\n=== 练习6:字符串判断 ===")
email := "test@example.com"
// 使用if语句判断email是否包含"@"
// 提示:使用strings.Contains函数
2026-03-14 20:39:58 +08:00
if strings.Contains(email, "@") {
2026-03-13 23:54:07 +08:00
return "有效的邮箱地址"
} else {
return "无效的邮箱地址"
}
}
func main() {
2026-03-14 20:39:58 +08:00
fmt.Println("=== if-else 练习 ===")
2026-03-13 23:54:07 +08:00
exercise1()
exercise2()
result3 := exercise3()
fmt.Println(result3)
result4 := exercise4()
fmt.Println(result4)
result5 := exercise5()
fmt.Printf("练习5结果: %t\n", result5)
result6 := exercise6()
fmt.Println(result6)
}