1 #include <stdio.h> 2 3 int main() 4 { 5 int choice; 6 7 printf("please input your number:"); 8 scanf("%d",&choice); 9 10 switch(choice) 11 { 12 case 1: 13 printf("HHKB pro2 "); 14 break; 15 case 2: 16 printf("chair "); 17 break; 18 case 3: 19 printf("screen "); 20 break; 21 case 4: 22 printf("computer key "); 23 break; 24 case 5: 25 printf("mouse "); 26 break; 27 default: 28 printf("thank you "); 29 } 30 31 32 return 0; 33 }
打印结果:
注:
1、if else if针对于范围的多路选择;而switch是针对点的多路选择,也可以小范围选择。
2、switch(表达式),中的表达式,必须为整型或字符型。
3、case只能为常量表达式,常量一般为整型常量。
4、case分支要同break连用,跳出switch。匹配一次后,不再匹配。
5、两case之间,可以用大括号。
6、switch结构表示:
switch(表达式)
{
case 常量 1:
代码块 1;
break;
case 常量 2:
代码块 2;
break;
default:
代码块 3;
break;//此处的break可以省略
}