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

122 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"strconv"
"strings"
)
func exercise1() {
fmt.Println("=== 练习1:简单if判断 ===")
age := 18
// 使用if语句,判断age是否大于等于18
// 如果是,输出"你已经成年了"
if age >= 18 {
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: 不及格
if score >= 90 {
fmt.Printf("分数: %d, 等级: 优秀\n", score)
} else if score >= 80 {
fmt.Printf("分数: %d, 等级: 良好\n", score)
} else if score >= 60 {
fmt.Printf("分数: %d, 等级: 及格\n", score)
} else {
fmt.Printf("分数: %d, 等级: 不及格\n", score)
}
}
func exercise3() string {
fmt.Println("\n=== 练习3:带初始化语句的if ===")
// 使用带初始化语句的if,将字符串"42"转换为整数
// 如果转换成功,返回字符串"转换成功: 转换后的值"
// 如果转换失败,返回字符串"转换失败"
if num, err := strconv.Atoi("42"); err == nil {
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. 账户是激活状态
// 三个条件都满足时,返回"登录成功",否则返回"登录失败"
if username == "admin" && password == "123456" && isActive == true {
return "登录成功"
} else {
return "登录失败"
}
}
func exercise5() bool {
fmt.Println("\n=== 练习5:逻辑非和或运算 ===")
hasPermission := false
isAdmin := true
// 使用if语句,判断"没有权限但可以是管理员"的情况
// 提示:使用 ! 或 ||
if hasPermission || isAdmin {
return true
}
return false
}
func exercise6() string {
fmt.Println("\n=== 练习6:字符串判断 ===")
email := "test@example.com"
// 使用if语句判断email是否包含"@"
// 提示:使用strings.Contains函数
if strings.Contains(email, "@") {
return "有效的邮箱地址"
} else {
return "无效的邮箱地址"
}
}
func main() {
fmt.Println("=== if-else 练习 ===")
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)
}