卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

在C语言中解释else-if梯形语句

这是编写多路决策的最通用方法。

语法

请参阅下面给出的语法 -

'
if (condition1)
stmt1;
else if (condition2)
stmt2;
- - - - -
- - - - -
else if (condition n)
stmtn;
else
stmt x;

在C语言中解释else-if梯形语句

算法

参考下面给出的算法 −

'
START
Step 1: Declare int variables.
Step 2: Read a,b,c,d values at runtime
Step 3: i. if(a>b && a>c && a>d)
Print a is largest
ii.else if(b>c && b>a && b>d)
Print b is largest
iii. else if(c>d && c>a && c>b)
Print c is largest
iv. else
print d is largest
STOP

示例

以下是执行Else If Ladder条件运算符的C程序 −

实时演示

'
#include<stdio.h>
void main (){
   int a,b,c,d;
   printf("Enter the values of a,b,c,d: ");
   scanf("%d%d%d%d",&a,&b,&c,&d);
   if(a>b && a>c && a>d){
      printf("%d is the largest",a);
   }else if(b>c && b>a && b>d){
      printf("%d is the largest",b);
   }else if(c>d && c>a && c>b){
      printf("%d is the largest",c);
   }else{
      printf("%d is the largest",d);
   }
}

输出

您将看到以下输出 −

'
Run 1:Enter the values of a,b,c,d: 2 4 6 8
8 is the largest
Run 2: Enter the values of a,b,c,d: 23 12 56 23
56 is the largest

考虑另一个 C 程序,它使用 else ifladder 显示学生的成绩 -

实时演示

'
#include<stdio.h>
int main(){
   int marks;
   printf("Enter the marks of a student:<p>");
   scanf("%d",&marks);
   if(marks <=100 && marks >= 90)
      printf("Grade=A");
   else if(marks < 90 && marks>= 80)
      printf("Grade=B");
   else if(marks < 80 && marks >= 70)
      printf("Grade=C");
   else if(marks < 70 && marks >= 60)
      printf("Grade=D");
   else if(marks < 60 && marks > 50)
      printf("Grade=E");
   else if(marks == 50)
      printf("Grade=F");
   else if(marks < 50 && marks >= 0)
      printf("Fail");
   else
      printf("Enter a valid score between 0 and 100");
   return 0;
}</p>

输出

您将看到以下输出 −

'
Run 1:
Enter the marks of a student:78
Grade=C
Run 2:
Enter the marks of a student:98
Grade=A
卓越飞翔博客
上一篇: 如何使用PHP编写一个将中文字符转换为拼音的函数?
下一篇: 如何在Nginx中配置反向代理以提高Web服务的性能和可靠性?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏