C Else If
else if 语句
如果第一个条件为false,则使用else if语句指定一个新的条件。
语法
if (condition1) {
// 如果条件1为真,则要执行的代码块
} else if (condition2) {
// 如果条件1为假且条件2为真,则执行以下代码块。
} else {
// 如果条件1和条件2都为假,则要执行的代码块
}
示例
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
亲自试一试 »
Example explained
在上面的例子中,时间(22)大于 10,因此第一个条件为 false。在 else if 语句中,下一个条件也为 false,所以我们继续执行 else 条件,因为 condition1 和 condition2 都为 false,并在屏幕上打印"Good evening"。
但是,如果时间是 14 点,程序会打印"Good day."

