嵌套的if-else
引入:
三个数如何比大小?
#include<stdio.h>
int main()
{
int a,b,c;
scanf("%d %d %d", &a, &b, &c);
int max = 0;
if ( a>b) {
if ( a>c ) {
max = a;
} else {
max = c;
}
} else {
if ( b>c ) {
max = b;
} else {
max = c;
}
printf("The max is &d\n", max);
return 0;
}
or
if ( a>b )
if ( a>c )
max = a;
else
max = c;
else
if ( b>c )
max = b;
else
max = c;
else的匹配
- else总是和最近的if匹配
- 缩进格式不能暗示else的匹配(python用对齐表示嵌套关系,c用花括号)
tips.
在if,else后面总是用{ },即使只有一条,养成良好习惯
级联的if-else
分段函数
-1; x<0
f(x)= 0; x=0
2x; x>0
if ( x<0) {
f = -1;
} else if ( x == 0 ) {
f = 0;
} else {
f = 2 * x;
}printf("%d", f)
第一个else对应第一个if,第二个else对应第二个if
级联的if-else if
if (exp1)
st1;
else if (exp2)
st2;
else
st3;
可以取消掉大括号,使所有的else对齐
多路分支
switch-case
eg1.
#include <stdio.h>
int main()
{
int type;
scanf("%d", &type);
if ( type==1 )
printf("你好");
else if ( type==2 )
printf("早上好");
else if ( type==3 )
printf("晚上好");
else if ( type==4 )
printf("再见");
else
printf("啊,什么啊?");
return 0;
}
需要一步步判断输入值是否等于1,2,3……
eg2.
#include <stdio.h>
int main()
{
int type;
scanf("%d", &type);
switch (type){
case 1:
printf("你好");
break;
case 2:
printf("早上好");
break;
case 3:
printf("晚上好");
break;
case 4:
printf("再见");
break;
default:
printf("啊,什么啊?");
}
return 0;
}
可以直接跳到指定值处
基本格式
switch (控制表达式) {
case 常量:
语句
……
case 常量
语句
……
default:
……
}
- 控制表达式只能是整数型的结果
- 常量可以是常数,也可以是常数计算的表达式
break switch语句可以看作一种基于计算机的跳转,分支标号只是说明switch内部位置的路标,在执行完分支中的最后一条语句后,若后面没有break,就会顺序执行到下面的case去,直到遇到一个break或switch结束为止
(case只是入口,不能阻止程序继续进行,break才行)