单行if语句
if (条件) {当条件为真时执行的语句}
#include<iostream>
#include<cmath>
using namespace std;
int main() {
cout << "输入你的分数" << endl;
int score = 0;
cin >> score;
if (score > 60)
{
cout << "你的成绩及格了" << endl;
}
return 0;
}
多行if语句
if (条件) {当条件为真时执行的语句} else {当条件为假时执行的语句}
#include<iostream>
#include<cmath>
using namespace std;
int main() {
cout << "输入你的分数" << endl;
int score = 0;
cin >> score;
if (score > 60)
{
cout << "你的成绩及格了" << endl;
}
else {
cout << "你的成绩不及格" << endl;
}
return 0;
}
多条件if语句
if (条件1) {当条件为真时执行的语句} else if (条件2){当条件1为假,条件2为真时执行的语句}......else{当前面的条件都为假时执行的语句}
#include<iostream>
#include<cmath>
using namespace std;
int main() {
cout << "输入你的分数" << endl;
int score = 0;
cin >> score;
if (score > 80)
{
cout << "你的成绩优秀了" << endl;
}
else if (score > 60)
{
cout << "你的成绩及格了" << endl;
}
else {
cout << "你的成绩不及格" << endl;
}
return 0;
}
嵌套if语句
可以执行更精细的条件控制,例如下面的例题,年龄小于18并且身高低于160cm时免票,我们可以先判断年龄是否小于18,再判断身高是否低于160cm
#include<iostream>
#include<cmath>
using namespace std;
int main() {
//成年人门票100元,年龄小于18并且身高低于160cm免票
int age, height;
cout << "请输入您的年龄和身高" << endl;
cin >> age >> height;
if (age < 18)
{
if (height < 160)
cout << "免票" << endl;
else
cout << "门票100元" << endl;
}
else {
cout << "门票100元" << endl;
}
return 0;
}