1.switch的用法
- switch后面的括号只能填整型表达式
- case后面的常量不能有重复的
- 可以没有default
switch(整型表达式)
{
case 整型常量1:
语句;
case 整型常量2:
语句;
case 整型常量3:
语句;
default:
语句;
}
2.switch的应用
#include<stdio.h>
int main()
{
int i,x;
printf("请输入分数:\n");
scanf("%d", &i);
x = i / 10;
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("fail\n");
break;
case 6:
printf("pass\n");
break;
case 7:
printf("common\n");
break;
case 8:
printf("good\n");
break;
case 9:
printf("excellent\n");
break;
case 10:
printf("full mark\n");
break;
default:
printf("error\n");
break;
}
return 0;
}
3.switch 中break的作用
#include<stdio.h>
int main()
{
int i,x;
printf("请输入分数:\n");
scanf("%d", &i);
x = i / 10;
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("fail\n");
case 6:
printf("pass\n");
case 7:
printf("common\n");
case 8:
printf("good\n");
case 9:
printf("excellent\n");
case 10:
printf("full mark\n");
default:
printf("error\n");
}
return 0;
}
从运行结果可以看出,如果语句中没有使用break,会依次执行完所有case语句。所以break在这里的作用的作用是跳出switch循环。
4.continue为什么不能用在switch中
#include<stdio.h>
int main()
{
int i, x;
printf("请输入分数:\n");
scanf("%d", &i);
x = i / 10;
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("fail\n");
break;
case 6:
printf("pass\n");
break;
case 7:
printf("common\n");
break;
case 8:
printf("good\n");
continue;
case 9:
printf("excellent\n");
break;
case 10:
printf("full mark\n");
break;
default:
printf("error\n");
break;
}
return 0;
}
switch是属于判断选择代码,是用于控制流程流转,而无法像for、do…while、while一样实现循环。所以在switch中无法使用continue。
5.switch死循环
#include<stdio.h>
int main()
{
int i, x;
printf("请输入分数:\n");
scanf("%d", &i);
x = i / 10;
for (; x <= 10;) {
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("fail\n");
break;
case 6:
printf("pass\n");
break;
case 7:
printf("common\n");
break;
case 8:
printf("good\n");
continue;//continue属于for循环
case 9:
printf("excellent\n");
break;
case 10:
printf("full mark\n");
break;
default:
printf("error\n");
break;
}
}
return 0;
}
输入89,程序将无限打印good:(因为continue结束本次循环,又重新开始下一轮循环)
标签:11,case,10,多重选择,C语言,break,switch,continue,printf From: https://blog.51cto.com/u_15420562/5729263