C++教程-C++ if-else语句

C++ if-else语句
在C++编程中,if语句用于测试条件。C++中有各种类型的if语句。
- if语句
- if-else语句
- 嵌套if语句
- if-else-if梯形语句
C++ if语句
C++的if语句用于测试条件。如果条件为真,则执行相应的代码。
if (condition) {
// 需要执行的代码
}
C++ if示例:
#include <iostream>
using namespace std;
int main() {
int num = 10;
if (num % 2 == 0) {
cout << "它是偶数";
}
return 0;
}
输出:
它是偶数
C++ if-else语句
C++的if-else语句也用于测试条件。如果条件为真,则执行if块中的代码;否则执行else块中的代码。
if (condition) {
// 如果条件为真执行的代码
} else {
// 如果条件为假执行的代码
}
C++ if-else示例:
#include <iostream>
using namespace std;
int main() {
int num = 11;
if (num % 2 == 0) {
cout << "它是偶数";
} else {
cout << "它是奇数";
}
return 0;
}
输出:
它是奇数
C++带用户输入的if-else示例:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "请输入一个数字:";
cin >> num;
if (num % 2 == 0) {
cout << "它是偶数" << endl;
} else {
cout << "它是奇数" << endl;
}
return 0;
}
输出:
请输入一个数字:11
它是奇数
输出:
请输入一个数字:12
它是偶数
C++ if-else-if梯形语句
C++的if-else-if梯形语句从多个条件中执行一个条件的代码块。
if (condition1) {
// 如果条件1为真执行的代码
} else if (condition2) {
// 如果条件2为真执行的代码
} else if (condition3) {
// 如果条件3为真执行的代码
} else {
// 如果所有条件都为假执行的代码
}
C++ if-else-if示例:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "请输入一个数字以检查成绩:";
cin >> num;
if (num < 0 || num > 100) {
cout << "错误的数字";
} else if (num >= 0 && num < 50) {
cout << "不及格";
} else if (num >= 50 && num < 60) {
cout << "D级";
} else if (num >= 60 && num < 70) {
cout << "C级";
} else if (num >= 70 && num < 80) {
cout << "B级";
} else if (num >= 80 && num < 90) {
cout << "A级";
} else if (num >= 90 && num <= 100) {
cout << "A+级";
}
return 0;
}
输出:
请输入一个数字以检查成绩:66
C级
输出:
请输入一个数字以检查成绩:-2
错误的数字