C++ if...else 语句
if 语句可以后跟一个可选的 else 语句,当布尔表达式为 false 时执行。
语法
C++ 中 if...else 语句的语法如下 −
if(boolean_expression) {
// 如果布尔表达式为 true,则执行语句
} else {
// 如果布尔表达式为 false,则执行语句
}
如果布尔表达式求值为 true,则执行 if block 中的代码,否则执行 else block 中的代码。
流程图
示例
#include <iostream>
using namespace std;
int main () {
// 本地变量声明:
int a = 100;
// 检查布尔条件
if( a < 20 ) {
// 如果条件为 true,则打印以下内容
cout << "a is less than 20;" << endl;
} else {
// 如果条件为 false,则打印以下内容
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
上述代码编译并执行后,将产生以下结果 −
a is not less than 20; value of a is : 100
if...else if...else 语句
if 语句可以后跟一个可选的 else if...else 语句,这对于使用单个 if...else if 语句测试多种条件非常有用。
使用 if、else if、else 语句时,需要注意以下几点。
一个 if 可以有零个或一个 else,且必须在所有 else if 之后。
一个 if 可以有零个或多个 else if,且它们必须在 else 之前。
一旦某个 else if 成功,后续的 else if 或 else 都不会再被测试。
语法
C++ 中 if...else if...else 语句的语法如下 −
if(boolean_expression 1) {
// 当布尔表达式 1 为 true 时执行
} else if( boolean_expression 2) {
// 当布尔表达式 2 为 true 时执行
} else if( boolean_expression 3) {
// 当布尔表达式 3 为 true 时执行
} else {
// 当上述所有条件都不为 true 时执行。
}
示例
#include <iostream>
using namespace std;
int main () {
// 本地变量声明:
int a = 100;
// 检查布尔条件
if( a == 10 ) {
// 如果条件为 true,则打印以下内容
cout << "Value of a is 10" << endl;
} else if( a == 20 ) {
// 如果 else if 条件为 true
cout << "Value of a is 20" << endl;
} else if( a == 30 ) {
// 如果 else if 条件为 true
cout << "Value of a is 30" << endl;
} else {
// 如果所有条件都不为 true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
上述代码编译并执行后,将产生以下结果 −
Value of a is not matching Exact value of a is : 100