📚 什么是条件判断?
if语句的作用
if语句让程序根据条件选择不同的执行路径,就像生活中的"如果...就..."。
- ✅ 实现分支逻辑
- ✅ 根据条件选择执行不同代码
- ✅ 让程序更加智能灵活
- ✅ 是编程的核心控制结构
if语句的基本语法
开始
↓
条件判断
↓
✓ 真 →
执行代码块
✗ 假 →
跳过
#include <iostream>
using namespace std;
int main() {
int age = 18;
if (age >= 18) {
cout << "你已经成年了!" << endl;
}
cout << "程序结束" << endl;
return 0;
}
💡 语法要点:
• if 后面跟着圆括号 ()
• 条件表达式结果为 true 或 false
• 代码块用花括号 {} 包裹
• 如果只有一条语句,花括号可以省略(但不推荐)
⚙️ if-else 双分支
if-else 结构
当条件为真时执行if块,否则执行else块,二选一。
#include <iostream>
using namespace std;
int main() {
int score;
cout << "请输入成绩:";
cin >> score;
if (score >= 60) {
cout << "恭喜你,及格了!" << endl;
} else {
cout << "很遗憾,不及格。" << endl;
}
return 0;
}
🎮 互动实验:成绩判断器
输入成绩,查看判断结果和生成的代码
输入成绩后点击"判断"...
🛠️ if-else if 多分支
多重条件判断
当有多个条件需要判断时,使用 if-else if-else 结构。
#include <iostream>
using namespace std;
int main() {
int score;
cout << "请输入成绩:";
cin >> score;
if (score >= 90) {
cout << "优秀!" << endl;
} else if (score >= 80) {
cout << "良好!" << endl;
} else if (score >= 60) {
cout << "及格!" << endl;
} else {
cout << "不及格!" << endl;
}
return 0;
}
💡 执行规则:
• 从上到下依次判断
• 一旦某个条件为真,执行对应代码块
• 执行后立即跳出整个结构
• 如果所有条件都为假,执行else块
🎯 等级评定器
输入分数,自动评定等级(优秀/良好/及格/不及格)
输入分数后点击"评定等级"...
🚀 逻辑运算符组合
使用 &&、||、! 组合条件
通过逻辑运算符可以构建复杂的条件表达式。
#include <iostream>
using namespace std;
int main() {
int age;
bool hasID;
cout << "请输入年龄:";
cin >> age;
cout << "是否有身份证(1=有,0=无):";
cin >> hasID;
if (age >= 18 && hasID) {
cout << "可以进入!" << endl;
} else {
cout << "禁止入内!" << endl;
}
if (age < 12 || age > 60) {
cout << "享受优惠票价" << endl;
}
if (!hasID) {
cout << "请出示身份证" << endl;
}
return 0;
}
💡 逻辑运算符:
• && 逻辑与:两个条件都为真才为真
• || 逻辑或:只要有一个为真就为真
• ! 逻辑非:真变假,假变真
• 可以使用括号改变优先级
布尔表达式的简化
#include <iostream>
using namespace std;
int main() {
bool isRainy = true;
int score = 85;
if (isRainy) {
cout << "下雨了" << endl;
}
if (score) {
cout << "分数有效" << endl;
}
return 0;
}
📝 实战练习
📝 小练习:条件判断
以下代码的输出是什么?
#include <iostream>
using namespace std;
int main() {
int x = 10;
if (x > 5)
if (x > 15)
cout << "A";
else
cout << "B";
return 0;
}
选择答案查看解析...