📚 什么是if嵌套?
嵌套的概念
在一个if语句的代码块中再写一个或多个if语句,形成多层判断结构。
- ✅ 实现多层次条件判断
- ✅ 处理复杂的业务逻辑
- ✅ 先判断大条件,再判断小条件
- ⚠️ 注意代码可读性,不要嵌套太深
基本语法结构
#include <iostream>
using namespace std;
int main() {
int age = 20;
bool hasTicket = true;
if (age >= 18) {
cout << "已成年" << endl;
if (hasTicket) {
cout << "可以入场" << endl;
} else {
cout << "请先购票" << endl;
}
} else {
cout << "未成年人禁止入内" << endl;
}
return 0;
}
💡 执行流程:
1. 先判断外层条件(age >= 18)
2. 如果为真,进入外层代码块
3. 再判断内层条件(hasTicket)
4. 根据内层条件执行相应代码
5. 如果外层条件为假,直接执行外层else
⚙️ 双层嵌套示例
成绩等级评定(含补考判断)
#include <iostream>
using namespace std;
int main() {
int score;
bool isRetake;
cout << "请输入成绩:";
cin >> score;
cout << "是否补考(1=是,0=否):";
cin >> isRetake;
if (score >= 60) {
cout << "及格" << endl;
if (score >= 90) {
cout << "等级:优秀" << endl;
} else if (score >= 80) {
cout << "等级:良好" << endl;
} else {
cout << "等级:中等" << endl;
}
} else {
cout << "不及格" << endl;
if (isRetake) {
cout << "安排补考" << endl;
} else {
cout << "需要重修" << endl;
}
}
return 0;
}
🎮 互动实验:学生评价系统
输入成绩和是否补考,查看评价结果
输入信息后点击"评价"...
🛠️ 多层嵌套技巧
三层嵌套示例
虽然不推荐过深嵌套,但有时确实需要多层判断。
#include <iostream>
using namespace std;
int main() {
int age, income;
bool hasJob;
cout << "年龄:";
cin >> age;
cout << "是否有工作(1=有,0=无):";
cin >> hasJob;
cout << "月收入:";
cin >> income;
if (age >= 18) {
cout << "成年人" << endl;
if (hasJob) {
cout << "有工作" << endl;
if (income >= 10000) {
cout << "高收入群体" << endl;
} else {
cout << "普通收入" << endl;
}
} else {
cout << "待业状态" << endl;
}
} else {
cout << "未成年人" << endl;
}
return 0;
}
⚠️ 注意事项:
• 嵌套层数建议不超过3层
• 每层都要正确缩进
• 可以使用逻辑运算符简化
• 考虑使用switch或函数重构
使用逻辑运算符替代嵌套
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool hasID = true;
bool hasTicket = true;
if (age >= 18) {
if (hasID) {
if (hasTicket) {
cout << "可以入场(嵌套)" << endl;
}
}
}
if (age >= 18 && hasID && hasTicket) {
cout << "可以入场(简化)" << endl;
}
return 0;
}
🚀 嵌套的最佳实践
提前返回减少嵌套
#include <iostream>
using namespace std;
int main() {
int age = 20;
bool hasID = true;
if (age >= 18) {
if (hasID) {
cout << "允许进入" << endl;
} else {
cout << "需要身份证" << endl;
}
} else {
cout << "年龄不足" << endl;
}
if (age < 18) {
cout << "年龄不足" << endl;
return 0;
}
if (!hasID) {
cout << "需要身份证" << endl;
return 0;
}
cout << "允许进入" << endl;
return 0;
}
💡 优化技巧:
• 先处理异常/边界情况
• 使用提前返回(return)
• 减少嵌套层级
• 提高代码可读性
📝 实战练习
📝 小练习:嵌套理解
以下代码会输出什么?
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
if (x > 5) {
if (y > 15) {
cout << "A";
} else {
cout << "B";
}
} else {
cout << "C";
}
return 0;
}
选择答案查看解析...
💻 编程挑战
题目:根据年龄和身份判断票价(成人/儿童/老人,学生有优惠)。
输入信息后点击"生成代码"...