选择结构程序设计
if 语句(条件选择语句)
If语句的三种形式
形式一:
格式:if (表达式) 语句
执行过程:
表达式
语句
非0
=0
main()
{
int x , y ;
x=20 ;
y=10 ;
if (x>y)
printf(“%d”,x);
}
没有”;”
形式二:
格式:if (表达式)
语句1
else
语句2
执行过程:
表达式
语句1
语句2
非0
=0
main()
{
int x , y ;
x=20 ;
y=10 ;
if (x>y)
printf(“%d”,x);
else
printf(“%d”,y);
}
形式三:
格式:if (表达式1) 语句1
else if (表达式2) 语句2
else if (表达式3) 语句3
……
else if (表达式m) 语句m
else 语句n
执行过程:
表达式1
语句1
非0
=0
表达式2
表达式3
语句n
语句3
语句2
非0
非0
=0
=0
例:if (number>500) cost= ;
else if (number>300) cost= ;
else if (number>100) cost= ;
else if (number>50) cost= ;
else cost=0 ;
必须有“ ;”
If 语句的嵌套
If语句中又包含一个或多个if语句称为if语句的嵌套。
实际上只要将前述if语句的形式1和2中的内嵌语句用一个if语句代替,即成为if语句的嵌套。
嵌套的if语句还可以嵌套另一个if语句,形成多重嵌套。
一般形式:
if (条件1)
if语句 来自淘豆网www.taodocs.com转载请标明出处.