C語言中的if語句用于基于條件執(zhí)行操作。通過使用if-else語句,您可以執(zhí)行基于條件為true或false的操作。
使用C語言中的if語句有很多形式:
if語句的語法如下 -
if(expression){
//code to be executed
}
C語言中的if語句的流程圖,如下所示 -

我們來看一個(gè)簡單的c語言if語句的示例代碼,創(chuàng)建一個(gè)源文件:if-statement.c,代碼如下所示 -
#include<stdio.h>
#include<conio.h>
void main() {
int number = 0;
printf("enter a number:");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is even number\n", number);
}
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
enter a number:100
100 is even number
如果condition為true或false都要執(zhí)行對應(yīng)代碼塊,則可使用C語言中的if-else語句來實(shí)現(xiàn)。if-else語句的語法如下:
if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
C語言中的if-else語句的流程圖,如下所示 -

我們來看一個(gè)簡單的C語言if-else語句的示例代碼,創(chuàng)建一個(gè)源文件:if-else-statement.c,代碼如下所示 -
#include<stdio.h>
#include<conio.h>
void main() {
int number = 0;
printf("enter a number:");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is even number\n", number);
}
else {
printf("%d is odd number\n", number);
}
}
執(zhí)行上面示例代碼,第一次執(zhí)行得到以下結(jié)果(輸入整數(shù):20),
enter a number:20
20 is even number
請按任意鍵繼續(xù). . .
第二次執(zhí)行得到以下結(jié)果(輸入整數(shù):55),
enter a number:55
55 is odd number
請按任意鍵繼續(xù). . .
if else-if語句用于從多個(gè)條件執(zhí)行一個(gè)代碼。 if 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 the conditions are false
}
C語言中的if else-if語句的流程圖 -

下面給出了C語言中if-else-if語句的例子,創(chuàng)建一個(gè)源文件:if-ifelse-statment.c,其代碼如下所示 -
#include<stdio.h>
void main() {
int number = 0;
printf("enter a number:");
scanf("%d", &number);
if (number == 10) {
printf("number is equals to 10\n");
}else if (number == 50) {
printf("number is equal to 50\n");
}else if (number == 100) {
printf("number is equal to 100\n");
}else {
printf("number is not equal to 10, 50 or 100\n");
}
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
enter a number:88
number is not equal to 10, 50 or 100
嵌套if語句就是在一個(gè)if語句中嵌套一個(gè)或多個(gè)if語句,創(chuàng)建一個(gè)源文件:nested_if.c,參考如下示例代碼:
#include<stdio.h>
void main() {
int score = 0;
printf("enter a score:");
scanf("%d", &score);
if (score >= 60) { // 下面是嵌套if-else語句
if (score <= 80) {
printf("分?jǐn)?shù)大于60小于80,中等水平\n");
}else if (score > 80 && score < 90) {
printf("分?jǐn)?shù)大于60小于80,成績良好\n");
}else{// 大于 90 以上
printf("分?jǐn)?shù)大于90,成績優(yōu)秀\n");
}
}else {
printf("分?jǐn)?shù)小于 60 分,不及格~!\n");
}
}
執(zhí)行上面查詢語句,得到以下結(jié)果 -
enter a score:90
分?jǐn)?shù)大于90,成績優(yōu)秀
請按任意鍵繼續(xù). . .