开关语句学习笔记:
多个分支:根据表达式的值的不同做出选择,决定下一步执行的操作。
即
switch语句语法形式为:
switch(表达式)
{
case 常量1:语句一 break;
case常量2 : 语句二 break;
case常量2: 语句三 break;
........
default: 语句序列n+1
}
注意:
表达式的类型和常量1~n的类型必须一致,只能是整形(字符型或枚举);
case起标号作用,要求后面的常量表达式的值各不相同;
语句序列最后一句为break,表示退出该条语句,无break则会一直执行后面的所有的case;
最后的default可省略不写。
例如:输入月份,输出对应英文;
#include <stdio.h>
int main()
{
int month;
scanf("%d",&month);
switch(month)
{
case 1: printf("January\n");break;
case 2: printf("February\n"); break;
case 3: printf("March\n"); break;
case 4: printf("April\n");break;
case 5: printf("May\n"); break;
case 6: printf("June\n");break;
case 7: printf("July\n"); break;
case 8: printf("August\n");break;
case 9: printf("September\n"); break;
case 10:printf("october\n"); break;
case 11: printf("November\n"); break;
case 12: printf("December\n");break;
default: printf("it's Wrong! \n ");
}
}
◆在 switch语句中合理使用 break,能表达不同执行流程
◆能使用 switchl的场合也可使用f语句
◆在使用if的地方使用 switch,要看是否满足 switch语句中各表达式的条件。
例如,某年是平年,输入月份和日期,计算这是该年的第几天?
#include <stdio.h>
int main()
{
int month,total,day;
printf("请输入月份:");
scanf("%d",&month);
printf("请输入日期:");
scanf("%d",&day);
switch(month)
{
case 1: total =day; break;
case 2: total =day+31; break;
case 3: total =day+31+28; break;
case 4: total =day+31+28+31;break;
case 5: total =day+31+28+31+30; break;
case 6: total =day+31+28+31+30+31; break;
case 7: total =day+31+28+31+30+31+30; break;
case 8: total =day+31+28+31+30+31+30+31; break;
case 9: total =day+31+28+31+39+31+39+31+31; break;
case 10:total =day+31+28+31+30+31+39+31+31+39; break;
case 11:total =day+31+28+31+38+31+38+31+31+39+31; break;
case 12:total =day+31+28+31+38+31+38+31+31+39+31; break;
}
printf("%d",total);
return 0;
}