C 语言中的 Else If 语句

当我们必须测试多个条件时,C 语言中的 Else If 语句就很有用。除了 Else If,我们也可以利用嵌套 If 语句来达到同样的目的。然而,随着条件数量的增加,代码的复杂性也会进一步增加。

C 语言中的 Else If 语句通过按顺序执行多个语句来有效地处理它们。编译器会检查第一个条件。如果条件结果为 TRUE(真),那么该块中的语句将会运行。如果结果为 FALSE(假),编译器会验证下一个(Else If 条件),以此类推。

C 语言中 Else If 语句的语法

Else If 语句的语法如下

if (condition 1)
          statements 1
else if (condition 2)
          statements 2
else if (condition 3)
          statements 3
      ...........
else if (condition n)
          statements n
else
    default statements

在某些情况下,condition1 和 condition2 可能都为 TRUE,例如

x = 20, y = 10

条件 1: x > y //TRUE

条件 2: x != y //TRUE

在这种情况下,Condition1 下的代码将被执行。因为 ELSE IF 条件只有在其前面的 IF 或 ELSE IF 语句失败时才会执行。

Else If 流程图

C 语言中 Else If 语句背后的编程流程图

Else If Flow Chart

C 语言中的 Else If 语句示例

在这个程序中,用户被要求输入他们六个科目的总分。我们将使用这个 Else if 语句来决定此人是否有资格获得奖学金。

/* Example */

#include <stdio.h> 

int main() 
{
 int Totalmarks; 
 
 //Imagine you have 6 subjects and Grand total is 600 
 printf("Please Enter your Total Marks\n" ); 
 scanf( "%d", &Totalmarks ); 

 if (Totalmarks >= 540) 
  {
    printf("You are eligible for Full Scholarship\n");
    printf("Congratulations\n");
  } 
 else if (Totalmarks >= 480) 
  {
    printf("You are eligible for 50 Percent Scholarship\n");
    printf("Congratulations\n");
  } 
 else if (Totalmarks >= 400) 
  {
    printf("You are eligible for 10 Percent Scholarship\n");
    printf("Congratulations\n");
  } 
 else 
  {
    printf("You are Not eligible for Scholarship\n");
    printf("We are really Sorry for You\n");
  }
}

输出 1:在此示例中,我们将提供 Totalmarks = 570。这里第一个 If 条件为 TRUE。也请参考嵌套 If 语句的文章。

Else If Statement in C Language 1

输出 2:这是为了演示 Else IF 语句。我们输入 Totalmarks = 490,意味着第一个 IF 条件为 FALSE。

它将检查 (Totalmarks >= 480),结果为 TRUE,因此程序将打印此块内的代码。尽管 else if(Totalmarks >= 400) 条件也为 TRUE,但编译器不会检查此条件。

Please Enter your Total Marks
490
You are eligible for 50 Percent Scholarship
Congratulations

第 3 个输出:总分为 401 – 第一个 IF 条件和 else if (Totalmarks >= 480) 均为 FALSE。接下来,它将检查 else if (Totalmarks >= 401),结果为 TRUE。因此它将打印这个代码块。

Please Enter your Total Marks
401
You are eligible for 10 Percent Scholarship
Congratulations

输出 4:让我输入总分 = 380。这表明所有的 IF 条件都失败了。因此,它会打印 else 块内的语句。

Please Enter your Total Marks
380
You are Not eligible for Scholarship
We are really Sorry for You