您的位置:首页 > 其它

浅谈switch-case的语法和应用

2015-08-22 10:09 309 查看
Switch-Case:

语法:

switch (整型/字符型表达式) {

case 值1:{

语句1

break;

}

case 值2:{

语句2

break;

}

......

case 值n:{

语句n

break;

}

default:{

语句n+1

break;

}

}

说明:

1、如果表达式的值没有和任何一个case后面的值匹配成功,程序直接执行default语句。

2、default分支如果没有语句,可以没有{},但是必须要有break。

3、break语句在switch中的作用:结束当前case分支的执行,并且结束switch语句。

4、多个case可以运行同一个代码段。

例1:输入生日,输出年龄(今年为2015年)和星座

白羊座 3.21-4.19

金牛座 4.20-5.20

双子座 5.21-6.21

巨蟹座 6.22-7.22

狮子座 7.23-8.22

处女座 8.23-9.22

天平座 9.23-10.23

天蝎座 10.24-11.22

射手座 11.23-12.21

摩羯座 12.22-1.19

水瓶座 1.20-2.18

双鱼座 2.19-3.20

int year = 0, mouth = 0, day = 0;

printf("Please enter birthday of someone(yy-mm-dd): \n");

scanf("%d-%d-%d",&year, &mouth, &day); // 输入年月日最好有格式的显示

int age = 2015 - year;

switch (mouth) {

case 1:{

if (day >= 20) {

printf("Age is %d, 星座是水瓶座。\n", age);

}else {

printf("Age is %d, 星座是摩羯座。\n", age);

}

break;

}

case 2:{

if (day >= 19) {

printf("Age is %d, 星座是双鱼座。\n", age);

}else {

printf("Age is %d, 星座是水瓶座。\n", age);

}

break;

}

case 3:{

if (day >= 21) {

printf("Age is %d, 星座是白羊座。\n", age);

}else {

printf("Age is %d, 星座是双鱼座。\n", age);

}

break;

}

case 4:{

if (day >= 20) {

printf("Age is %d, 星座是金牛座。\n", age);

}else {

printf("Age is %d, 星座是白羊座。\n", age);

}

break;

}

case 5:{

if (day >= 21) {

printf("Age is %d, 星座是双子座。\n", age);

}else {

printf("Age is %d, 星座是金牛座。\n", age);

}

break;

}

case 6:{

if (day >= 22) {

printf("Age is %d, 星座是巨蟹座。\n", age);

}else {

printf("Age is %d, 星座是双子座。\n", age);

}

break;

}

case 7:{

if (day >= 23) {

printf("Age is %d, 星座是狮子座。\n", age);

}else {

printf("Age is %d, 星座是巨蟹座。\n", age);

}

break;

}

case 8:{

if (day >= 23) {

printf("Age is %d, 星座是处女座。\n", age);

}else {

printf("Age is %d, 星座是狮子座。\n", age);

}

break;

}

case 9:{

if (day >= 23) {

printf("Age is %d, 星座是天秤座。\n", age);

}else {

printf("Age is %d, 星座是处女座。\n", age);

}

break;

}

case 10:{

if (day >= 24) {

printf("Age is %d, 星座是天蝎座。\n", age);

}else {

printf("Age is %d, 星座是天秤座。\n", age);

}

break;

}

case 11:{

if (day >= 23) {

printf("Age is %d, 星座是射手座。\n", age);

}else {

printf("Age is %d, 星座是天蝎座。\n", age);

}

break;

}

case 12:{

if (day >= 22) {

printf("Age is %d, 星座是摩羯座。\n", age);

}else {

printf("Age is %d, 星座是射手座。\n", age);

}

break;

}

default:

break;

}

运行结果:

输入1990-01-28

显示:Age is 25,星座是水瓶座。

例2:按照考试成绩(A、B、C、D)的等级输出百分制分数段。A、B、C: 输出“60分以上” D:输出“60分以下”

// 多个case可以运行同一个代码段

char level = 'A';

switch (level) {

case 'A':

case 'B':

case 'C':{

printf("60分以上 \n");

break;

}

case 'D':{

printf("60分以下 \n");

break;

}

default:

break;

}

运行结果:60分以上。

说明:因break可以结束当前case分支的执行,并且结束switch语句。所以可以合并相同功能的case语句,只保留最后一个break语句以结束程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: