if语句
C语言中的if语句用于执行给定条件下的一部分代码。
if语句的语法如下:
if (condition) {
// code to be executed if condition is true
}
在这里,condition
是一个表达式,如果为真,则执行if
语句块中的代码。如果条件为假,则跳过if
语句块中的代码。
下面是一个使用if语句的示例:
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
在这个示例中,如果变量num
的值大于0,则打印出"The number is positive."。否则,什么也不做。
else语句
else语句用于在if语句的条件为假时执行特定的代码块。
else必须与if配对使用
以下是else语句的一般语法:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
在这里,如果条件为真,则执行if语句块中的代码。如果条件为假,则执行else语句块中的代码。
下面是一个使用else语句的示例:
#include <stdio.h>
int main() {
int num = 5;
if (num % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
return 0;
}
在这个示例中,如果变量num
能够被2整除,则打印出"The number is even."。否则,打印出"The number is odd."。
注意,else语句不需要条件,它只会在前面的if语句的条件为假时执行。
else if语句
else if语句可以用来在if语句的条件为假时检查多个条件,并根据这些条件执行特定的代码块。else if语句可以与if语句和else语句一起使用,以处理多个可能的情况。
以下是else if语句的一般语法:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all conditions are false
}
在这里,首先判断condition1的值,如果为真,则执行相应的代码块。如果condition1为假,则继续判断condition2的值,以此类推。如果所有条件都为假,则执行else语句块中的代码。
下面是一个使用else if语句的示例:
#include <stdio.h>
int main() {
int num = 75;
if (num >= 90) {
printf("Grade A\n");
} else if (num >= 80) {
printf("Grade B\n");
} else if (num >= 70) {
printf("Grade C\n");
} else if (num >= 60) {
printf("Grade D