前言
上一篇我们学习了 C++ 变量、数据类型和输入输出。 今天来学习条件判断语句,让程序可以根据不同情况执行不同逻辑。
一、if 语句
满足条件时,才执行里面的代码。
cpp
#include
using namespace std;
int main() {
int score = 95;
if (score >= 60) {
cout << "成绩及格" << endl;
}
return 0;
}
二、if…else 语句
条件成立执行 if,不成立执行 else。
#include
using namespace std;
int main() {
int score = 50;
if (score >= 60) {
cout << "成绩及格" << endl;
} else {
cout << "成绩不及格" << endl;
}
return 0;
}
三、if…else if…else 多条件判断
适合多个分段判断,比如成绩分级。
cpp
#include
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;
}
四、比较运算符
条件中常用:
- > 大于
- < 小于
- >= 大于等于
- <= 小于等于
- == 等于
- != 不等于
五、总结
1. if 单独判断:条件成立才执行 2. if…else :二选一执行 3. if…else if…else :多条件分支 4. 条件里必须用布尔表达式(结果为真或假)
下一篇我们学习:循环语句 for / while / do-while