else if和连续if的区别
两者的区别关键在于,前者最多只会执行一次,而后者是有可能执行多次的
实例:使用if…else语句模拟信号灯
#include<stdio.h>
int main()
{
int iSignal; /*定义变量表示信号灯的状态*/
printf("the Red Light is 0,\nthe Green Light is 1,\nthe Yellow Light is other number\n"); /*输出提示信息*/
scanf("%d",&iSignal); /*输入iSignal变量*/
if(iSignal==1) /*当信号灯为绿色时*/
{
printf("the Light is green,cars can run\n");/*判断结果为真时输出*/
}
if(iSignal==0) /*当信号灯为红灯时*/
{
printf("the Light is red,cars can't run\n"); /*判断结果为真时输出*/
}
else /*当信号灯为黄灯时*/
{
printf("the Light is yellow,cars are ready\n");
}
return 0;
}
假如用户输入的值为1,程序会判断为真,接着就会执行下一条语句
实例:使用ielse if语句模拟信号灯
#include<stdio.h>
int main()
{
int iSignal;
while(1)
{
printf("the Red Light is 0,\nthe Green Light is 1,\nthe Yellow Light is other number\n"); /*输出提示信息*/
scanf("%d",&iSignal);
}
if(iSignal==1) /*当信号灯为绿色时*/
{
printf("the Light is green,cars can run\n");/*判断结果为真时输出*/
}
else if(iSignal==0) /*当信号灯为红灯时*/
{
printf("the Light is red,cars can't run\n"); /*判断结果为真时输出*/
}
else /*当信号灯为黄灯时*/
{
printf("the Light is yellow,cars are ready\n");
}
return 0;
}