C++ Else if


else if 语句

使用else if如果第一个条件是,则指定新条件的语句false

语法

if ( condition1) {
  // block of code to be executed if condition1 is true
} else if ( condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}

示例

int time = 22;
if (time < 10) {
  cout << "Good morning.";
} else if (time < 20) {
  cout << "Good day.";
} else {
  cout << "Good evening.";
}
// Outputs "Good evening."
亲自试一试 »

示例解释

在上例中,时间 (22) 大于 10,因此第一个条件false。下一个条件,在else if的声明,也是false,所以我们继续else条件自条件1条件2既是false- 并打印到屏幕"Good evening"。

但是,如果时间是 14,我们的程序将打印"Good day."