有关C语言if else语句的用法很简单,大致可以分为三种:
1.当有多个条件要判断时连续用if语句:
if(条件1)
if(条件2)
if(条件3)
……
#include<stdio.h>
int main()
{
int score[5];
int i;
printf("Please Enter your five subjects'scores:\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &score[i]);
}
for(i = 0; i < 5; i++)
{
if(score[i] >= 90)
{
printf("Your NO.%d subject is excellent!\n", i+1);
}
if(score[i] >= 80 && score[i] < 90)
{
printf("Your NO.%d subject is good!\n", i+1);
}
if(score[i] >= 60 && score[i] < 80)
{
printf("Your NO.%d subject is just so so!\n", i+1);
}
if(score[i] < 60)
{
printf("Your NO.%d subject is fail!\n", i+1);
}
}
return 0;
}
2.当只有两个相反条件需要判断的时候就用如下格式:
if(条件)
else//这里是不要条件的,条件就是if语句条件的相反情况。
#include<stdio.h>
int main()
{
int number = 0;
printf("If you like computer program, you can enter 1, or enter else number!\n");
scanf("%d", &number);
if(number == 1)
{
printf("Congratulation! Please study on https://blog.csdn.net/weixin_41588502!\n");
}
else
{
printf("What are you interested in?\n");
}
return 0;
}
3.这种形式与第一种相似,只是用法变成了另一种形式:
if(条件1)
else if(条件2)
else if(条件3)
……
else
#include<stdio.h>
int main()
{
int score[5];
int i;
printf("Please Enter your five subjects'scores:\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &score[i]);
}
for(i = 0; i < 5; i++)
{
if(score[i] >= 90)
{
printf("Your NO.%d subject is excellent!\n", i+1);
}
else if(score[i] >= 80)
{
printf("Your NO.%d subject is good!\n", i+1);
}
else if(score[i] >= 60)
{
printf("Your NO.%d subject is just so so!\n", i+1);
}
else
{
printf("Your NO.%d subject is fail!\n", i+1);
}
}
return 0;
}