使用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."
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!