485 lines
12 KiB
Go
485 lines
12 KiB
Go
/*
|
||
01-if-else.go - Go 语言条件语句详解
|
||
|
||
学习目标:
|
||
1. 掌握 if 语句的基本用法
|
||
2. 理解 if-else 和 if-else if 结构
|
||
3. 学会在 if 语句中声明变量
|
||
4. 了解条件表达式的写法
|
||
5. 掌握嵌套条件语句
|
||
|
||
知识点:
|
||
- if 语句基本语法
|
||
- if-else 语句
|
||
- if-else if-else 链
|
||
- if 语句中的变量声明
|
||
- 条件表达式
|
||
- 嵌套 if 语句
|
||
- 实际应用场景
|
||
*/
|
||
|
||
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"strconv"
|
||
"strings"
|
||
)
|
||
|
||
func main() {
|
||
fmt.Println("=== Go 语言条件语句详解 ===\n")
|
||
|
||
// 演示基本 if 语句
|
||
demonstrateBasicIf()
|
||
|
||
// 演示 if-else 语句
|
||
demonstrateIfElse()
|
||
|
||
// 演示 if-else if 链
|
||
demonstrateIfElseIf()
|
||
|
||
// 演示 if 语句中的变量声明
|
||
demonstrateIfWithDeclaration()
|
||
|
||
// 演示嵌套 if 语句
|
||
demonstrateNestedIf()
|
||
|
||
// 演示复杂条件表达式
|
||
demonstrateComplexConditions()
|
||
|
||
// 演示实际应用示例
|
||
demonstratePracticalExamples()
|
||
}
|
||
|
||
// demonstrateBasicIf 演示基本 if 语句
|
||
func demonstrateBasicIf() {
|
||
fmt.Println("1. 基本 if 语句:")
|
||
|
||
// 最简单的 if 语句
|
||
age := 18
|
||
if age >= 18 {
|
||
fmt.Printf(" 年龄 %d >= 18,已成年\n", age)
|
||
}
|
||
|
||
// 条件为 false 的情况
|
||
score := 45
|
||
if score >= 60 {
|
||
fmt.Printf(" 分数 %d >= 60,及格\n", score)
|
||
}
|
||
fmt.Printf(" 分数 %d < 60,条件不满足,if 块不执行\n", score)
|
||
|
||
// 布尔变量作为条件
|
||
isLoggedIn := true
|
||
if isLoggedIn {
|
||
fmt.Printf(" 用户已登录\n")
|
||
}
|
||
|
||
// 函数返回值作为条件
|
||
if isEven(10) {
|
||
fmt.Printf(" 10 是偶数\n")
|
||
}
|
||
|
||
// 注意:Go 的 if 语句不需要括号,但需要大括号
|
||
fmt.Printf(" 注意: Go 的 if 条件不需要括号,但大括号是必需的\n")
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// demonstrateIfElse 演示 if-else 语句
|
||
func demonstrateIfElse() {
|
||
fmt.Println("2. if-else 语句:")
|
||
|
||
// 基本 if-else
|
||
temperature := 25
|
||
if temperature > 30 {
|
||
fmt.Printf(" 温度 %d°C,天气炎热\n", temperature)
|
||
} else {
|
||
fmt.Printf(" 温度 %d°C,天气凉爽\n", temperature)
|
||
}
|
||
|
||
// 数值比较
|
||
a, b := 10, 20
|
||
if a > b {
|
||
fmt.Printf(" %d > %d\n", a, b)
|
||
} else {
|
||
fmt.Printf(" %d <= %d\n", a, b)
|
||
}
|
||
|
||
// 字符串比较
|
||
password := "123456"
|
||
if password == "admin123" {
|
||
fmt.Printf(" 密码正确\n")
|
||
} else {
|
||
fmt.Printf(" 密码错误\n")
|
||
}
|
||
|
||
// 布尔值判断
|
||
hasPermission := false
|
||
if hasPermission {
|
||
fmt.Printf(" 有权限访问\n")
|
||
} else {
|
||
fmt.Printf(" 没有权限访问\n")
|
||
}
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// demonstrateIfElseIf 演示 if-else if 链
|
||
func demonstrateIfElseIf() {
|
||
fmt.Println("3. if-else if-else 链:")
|
||
|
||
// 成绩等级判断
|
||
score := 85
|
||
fmt.Printf(" 分数: %d\n", score)
|
||
if score >= 90 {
|
||
fmt.Printf(" 等级: A (优秀)\n")
|
||
} else if score >= 80 {
|
||
fmt.Printf(" 等级: B (良好)\n")
|
||
} else if score >= 70 {
|
||
fmt.Printf(" 等级: C (中等)\n")
|
||
} else if score >= 60 {
|
||
fmt.Printf(" 等级: D (及格)\n")
|
||
} else {
|
||
fmt.Printf(" 等级: F (不及格)\n")
|
||
}
|
||
|
||
// 年龄段分类
|
||
age := 25
|
||
fmt.Printf(" 年龄: %d\n", age)
|
||
if age < 13 {
|
||
fmt.Printf(" 年龄段: 儿童\n")
|
||
} else if age < 20 {
|
||
fmt.Printf(" 年龄段: 青少年\n")
|
||
} else if age < 60 {
|
||
fmt.Printf(" 年龄段: 成年人\n")
|
||
} else {
|
||
fmt.Printf(" 年龄段: 老年人\n")
|
||
}
|
||
|
||
// BMI 指数判断
|
||
weight, height := 70.0, 1.75
|
||
bmi := weight / (height * height)
|
||
fmt.Printf(" BMI: %.1f\n", bmi)
|
||
if bmi < 18.5 {
|
||
fmt.Printf(" 体重状况: 偏瘦\n")
|
||
} else if bmi < 24 {
|
||
fmt.Printf(" 体重状况: 正常\n")
|
||
} else if bmi < 28 {
|
||
fmt.Printf(" 体重状况: 偏胖\n")
|
||
} else {
|
||
fmt.Printf(" 体重状况: 肥胖\n")
|
||
}
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// demonstrateIfWithDeclaration 演示 if 语句中的变量声明
|
||
func demonstrateIfWithDeclaration() {
|
||
fmt.Println("4. if 语句中的变量声明:")
|
||
|
||
// 在 if 语句中声明变量
|
||
if num := 42; num > 0 {
|
||
fmt.Printf(" 在 if 中声明: num = %d > 0\n", num)
|
||
// num 在这个 if 块中可用
|
||
}
|
||
// num 在这里不可用
|
||
|
||
// 实际应用:字符串转数字
|
||
str := "123"
|
||
if value, err := strconv.Atoi(str); err == nil {
|
||
fmt.Printf(" 字符串 \"%s\" 转换为数字: %d\n", str, value)
|
||
} else {
|
||
fmt.Printf(" 字符串 \"%s\" 转换失败: %v\n", str, err)
|
||
}
|
||
|
||
// 检查字符串长度
|
||
username := "admin"
|
||
if length := len(username); length >= 5 {
|
||
fmt.Printf(" 用户名 \"%s\" 长度 %d >= 5,符合要求\n", username, length)
|
||
} else {
|
||
fmt.Printf(" 用户名 \"%s\" 长度 %d < 5,太短\n", username, length)
|
||
}
|
||
|
||
// 计算并判断
|
||
if result := calculateDiscount(1000); result > 0 {
|
||
fmt.Printf(" 购买金额 1000,折扣: %.2f\n", result)
|
||
} else {
|
||
fmt.Printf(" 购买金额 1000,无折扣\n")
|
||
}
|
||
|
||
// 多个变量声明
|
||
if x, y := 10, 20; x+y > 25 {
|
||
fmt.Printf(" x=%d, y=%d, x+y=%d > 25\n", x, y, x+y)
|
||
}
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// demonstrateNestedIf 演示嵌套 if 语句
|
||
func demonstrateNestedIf() {
|
||
fmt.Println("5. 嵌套 if 语句:")
|
||
|
||
// 用户登录验证
|
||
username := "admin"
|
||
password := "123456"
|
||
isActive := true
|
||
|
||
fmt.Printf(" 用户登录验证:\n")
|
||
if username == "admin" {
|
||
fmt.Printf(" 用户名正确\n")
|
||
if password == "123456" {
|
||
fmt.Printf(" 密码正确\n")
|
||
if isActive {
|
||
fmt.Printf(" 账户状态: 活跃\n")
|
||
fmt.Printf(" 登录成功!\n")
|
||
} else {
|
||
fmt.Printf(" 账户状态: 已禁用\n")
|
||
fmt.Printf(" 登录失败: 账户被禁用\n")
|
||
}
|
||
} else {
|
||
fmt.Printf(" 密码错误\n")
|
||
fmt.Printf(" 登录失败: 密码不正确\n")
|
||
}
|
||
} else {
|
||
fmt.Printf(" 用户名错误\n")
|
||
fmt.Printf(" 登录失败: 用户不存在\n")
|
||
}
|
||
|
||
// 数值范围判断
|
||
number := 15
|
||
fmt.Printf(" 数值范围判断 (number = %d):\n", number)
|
||
if number > 0 {
|
||
fmt.Printf(" 数值为正数\n")
|
||
if number < 10 {
|
||
fmt.Printf(" 数值 < 10,属于个位数\n")
|
||
} else if number < 100 {
|
||
fmt.Printf(" 数值 < 100,属于两位数\n")
|
||
} else {
|
||
fmt.Printf(" 数值 >= 100,属于三位数或更多\n")
|
||
}
|
||
} else if number < 0 {
|
||
fmt.Printf(" 数值为负数\n")
|
||
} else {
|
||
fmt.Printf(" 数值为零\n")
|
||
}
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// demonstrateComplexConditions 演示复杂条件表达式
|
||
func demonstrateComplexConditions() {
|
||
fmt.Println("6. 复杂条件表达式:")
|
||
|
||
// 逻辑与条件
|
||
age := 25
|
||
hasLicense := true
|
||
hasInsurance := true
|
||
|
||
if age >= 18 && hasLicense && hasInsurance {
|
||
fmt.Printf(" 年龄: %d, 有驾照: %t, 有保险: %t\n", age, hasLicense, hasInsurance)
|
||
fmt.Printf(" 可以开车\n")
|
||
}
|
||
|
||
// 逻辑或条件
|
||
isWeekend := false
|
||
isHoliday := true
|
||
|
||
if isWeekend || isHoliday {
|
||
fmt.Printf(" 周末: %t, 假日: %t\n", isWeekend, isHoliday)
|
||
fmt.Printf(" 今天不用上班\n")
|
||
}
|
||
|
||
// 复合条件
|
||
temperature := 28
|
||
humidity := 70
|
||
|
||
if (temperature > 25 && humidity > 60) || temperature > 35 {
|
||
fmt.Printf(" 温度: %d°C, 湿度: %d%%\n", temperature, humidity)
|
||
fmt.Printf(" 天气闷热,建议开空调\n")
|
||
}
|
||
|
||
// 字符串条件
|
||
email := "user@example.com"
|
||
if strings.Contains(email, "@") && strings.Contains(email, ".") {
|
||
fmt.Printf(" 邮箱 \"%s\" 格式基本正确\n", email)
|
||
}
|
||
|
||
// 数值范围条件
|
||
score := 75
|
||
if score >= 0 && score <= 100 {
|
||
fmt.Printf(" 分数 %d 在有效范围内\n", score)
|
||
if score >= 60 {
|
||
fmt.Printf(" 及格\n")
|
||
} else {
|
||
fmt.Printf(" 不及格\n")
|
||
}
|
||
} else {
|
||
fmt.Printf(" 分数 %d 超出有效范围\n", score)
|
||
}
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// demonstratePracticalExamples 演示实际应用示例
|
||
func demonstratePracticalExamples() {
|
||
fmt.Println("7. 实际应用示例:")
|
||
|
||
// 示例1: 银行账户操作
|
||
fmt.Printf(" 示例1 - 银行账户操作:\n")
|
||
balance := 1000.0
|
||
withdrawAmount := 500.0
|
||
|
||
if withdrawAmount > 0 {
|
||
if withdrawAmount <= balance {
|
||
balance -= withdrawAmount
|
||
fmt.Printf(" 取款成功,取款金额: %.2f,余额: %.2f\n", withdrawAmount, balance)
|
||
} else {
|
||
fmt.Printf(" 取款失败,余额不足。余额: %.2f,尝试取款: %.2f\n", balance, withdrawAmount)
|
||
}
|
||
} else {
|
||
fmt.Printf(" 取款失败,金额必须大于0\n")
|
||
}
|
||
|
||
// 示例2: 文件权限检查
|
||
fmt.Printf(" 示例2 - 文件权限检查:\n")
|
||
const (
|
||
READ = 1 << 0 // 001
|
||
WRITE = 1 << 1 // 010
|
||
EXECUTE = 1 << 2 // 100
|
||
)
|
||
|
||
permissions := READ | WRITE // 011
|
||
operation := "write"
|
||
|
||
if operation == "read" {
|
||
if permissions&READ != 0 {
|
||
fmt.Printf(" 允许读取文件\n")
|
||
} else {
|
||
fmt.Printf(" 没有读取权限\n")
|
||
}
|
||
} else if operation == "write" {
|
||
if permissions&WRITE != 0 {
|
||
fmt.Printf(" 允许写入文件\n")
|
||
} else {
|
||
fmt.Printf(" 没有写入权限\n")
|
||
}
|
||
} else if operation == "execute" {
|
||
if permissions&EXECUTE != 0 {
|
||
fmt.Printf(" 允许执行文件\n")
|
||
} else {
|
||
fmt.Printf(" 没有执行权限\n")
|
||
}
|
||
}
|
||
|
||
// 示例3: 购物折扣计算
|
||
fmt.Printf(" 示例3 - 购物折扣计算:\n")
|
||
purchaseAmount := 800.0
|
||
customerLevel := "gold"
|
||
isFirstPurchase := false
|
||
|
||
var discount float64
|
||
var discountReason string
|
||
|
||
if customerLevel == "platinum" {
|
||
discount = 0.2
|
||
discountReason = "白金会员"
|
||
} else if customerLevel == "gold" {
|
||
discount = 0.15
|
||
discountReason = "黄金会员"
|
||
} else if customerLevel == "silver" {
|
||
discount = 0.1
|
||
discountReason = "银牌会员"
|
||
} else {
|
||
discount = 0.05
|
||
discountReason = "普通会员"
|
||
}
|
||
|
||
// 首次购买额外折扣
|
||
if isFirstPurchase {
|
||
discount += 0.05
|
||
discountReason += " + 首次购买"
|
||
}
|
||
|
||
// 大额购买额外折扣
|
||
if purchaseAmount >= 1000 {
|
||
discount += 0.05
|
||
discountReason += " + 大额购买"
|
||
}
|
||
|
||
finalAmount := purchaseAmount * (1 - discount)
|
||
fmt.Printf(" 购买金额: %.2f\n", purchaseAmount)
|
||
fmt.Printf(" 客户等级: %s\n", customerLevel)
|
||
fmt.Printf(" 首次购买: %t\n", isFirstPurchase)
|
||
fmt.Printf(" 折扣原因: %s\n", discountReason)
|
||
fmt.Printf(" 折扣率: %.1f%%\n", discount*100)
|
||
fmt.Printf(" 最终金额: %.2f\n", finalAmount)
|
||
|
||
// 示例4: 时间段判断
|
||
fmt.Printf(" 示例4 - 时间段判断:\n")
|
||
hour := 14
|
||
|
||
var timeOfDay string
|
||
var greeting string
|
||
|
||
if hour >= 5 && hour < 12 {
|
||
timeOfDay = "上午"
|
||
greeting = "早上好"
|
||
} else if hour >= 12 && hour < 18 {
|
||
timeOfDay = "下午"
|
||
greeting = "下午好"
|
||
} else if hour >= 18 && hour < 22 {
|
||
timeOfDay = "晚上"
|
||
greeting = "晚上好"
|
||
} else {
|
||
timeOfDay = "深夜"
|
||
greeting = "夜深了"
|
||
}
|
||
|
||
fmt.Printf(" 当前时间: %d:00\n", hour)
|
||
fmt.Printf(" 时间段: %s\n", timeOfDay)
|
||
fmt.Printf(" 问候语: %s\n", greeting)
|
||
|
||
fmt.Println()
|
||
}
|
||
|
||
// 辅助函数
|
||
func isEven(n int) bool {
|
||
return n%2 == 0
|
||
}
|
||
|
||
func calculateDiscount(amount float64) float64 {
|
||
if amount >= 1000 {
|
||
return amount * 0.1 // 10% 折扣
|
||
} else if amount >= 500 {
|
||
return amount * 0.05 // 5% 折扣
|
||
}
|
||
return 0 // 无折扣
|
||
}
|
||
|
||
/*
|
||
运行这个程序:
|
||
go run 01-if-else.go
|
||
|
||
学习要点:
|
||
1. if 语句的条件不需要括号,但大括号是必需的
|
||
2. 可以在 if 语句中声明变量,作用域仅限于 if-else 块
|
||
3. if-else if-else 链可以处理多个条件分支
|
||
4. 支持复杂的条件表达式,使用 &&、|| 等逻辑运算符
|
||
5. 嵌套 if 语句可以处理复杂的逻辑判断
|
||
6. Go 没有三元运算符,使用 if-else 代替
|
||
|
||
最佳实践:
|
||
1. 条件表达式要清晰易懂
|
||
2. 避免过深的嵌套,考虑提前返回或使用函数分解
|
||
3. 复杂条件可以提取为变量或函数
|
||
4. 使用有意义的变量名和注释
|
||
5. 考虑使用 switch 语句替代长的 if-else if 链
|
||
|
||
常见应用场景:
|
||
1. 用户输入验证
|
||
2. 权限检查
|
||
3. 数值范围判断
|
||
4. 状态判断
|
||
5. 错误处理
|
||
6. 业务逻辑分支
|
||
*/ |