Menu
CoddyTech

else-if 语句

本课属于 Coddy C 学习旅程的“基础知识”单元。第 27 课,共 63 课。

else-if 语句可以让你依次检查多个条件。第一个 if 条件不成立时,程序会继续检查下一个 else-if 条件,以此类推。

先从一个基本的 if 语句开始:

if (grade >= 90) {
    printf("A grade\n");
}

添加一个 else-if 来检查另一个条件:

if (grade >= 90) {
    printf("A grade\n");
} else if (grade >= 80) {
    printf("B grade\n");
} else if (grade >= 70) {
    printf("C grade\n");
}

最后,你可以在末尾添加一个 else 语句来处理所有其他情况:

if (grade >= 90) {
    printf("A grade\n");
} else if (grade >= 80) {
    printf("B grade\n");
} else if (grade >= 70) {
    printf("C grade\n");
} else {
    printf("Failed\n");
}
challenge icon

挑战

简单

编写一个程序,输入温度值和一个表示温标的字符('C' 或 'F')。根据摄氏温度,打印以下消息之一:

  • 如果温度 < 0°C:“Freezing”
  • 如果温度在 0°C 到 20°C 之间:“Cold”
  • 如果温度在 21°C 到 30°C 之间:“Pleasant”
  • 如果温度 > 30°C:“Hot”

如果输入的是华氏温度,请先使用公式 C = (F - 32) * 5/9 将其转换为摄氏温度。

根据温度,严格按照上面所示打印消息。

亲手试试

#include <stdio.h>

int main() {
    int temperature;
    char scale;
    scanf("%d", &temperature);
    scanf(" %c", &scale);
    // 不要修改这行上面的代码
    
    // 在这里编写你的代码
    
    return 0;
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: C 在线编译器