知识点1 开关语句
格式:switch(表达式)
case1 :语句1;
case2 : 语句2;
......
default : 语句;
首先计算表达式,再与常量表达式相比,与对应的常量表达式输出其语句,若没有对应的常量表达式,则输出default后的语句。
例如:
#include<stdio.h>
int main()
{
int a,b;
scanf("%d %d",&a,&b);
switch (a+b) {
case 5:printf("A\n");
break;
case 10:printf("B\n");
break;
default:printf("C\N");
break;
}
return 0;
}
a=2,b=8;则输出结果:
2
8
B
--------------------------------
Process exited after 4.757 seconds with return value 0
请按任意键继续. . .
如果将其中的break去掉,那结果会变成怎样呢
#include<stdio.h>
int main()
{
int a,b;
scanf("%d %d",&a,&b);
switch (a+b) {
case 5:printf("A\n");
case 10:printf("B\n");
default:printf("C\N");
break;
}
return 0;
}
同样的a=2,b=8;结果会是这样的:
2
8
B
C
--------------------------------
Process exited after 2.627 seconds with return value 0
请按任意键继续. . .
会输出B C。
心得:开关语句要时刻注意细节,在很多地方很容易缺失。