这是谭浩强课本上枚举类型的例子,但是我贴这个例子的代码不是因为枚举类型,是因为这个代码使用switch语句用得非常好,值得一贴。
题目是这样的:有红、黄、蓝、白、黑5中颜色的球若干,依次取出3个球,求3个球为不同颜色时的排列方式。
1 #include<stdio.h> 2 3 int main(){ 4 enum color {red,yellow,blue,white,black}; 5 enum color i,j,k,pri; 6 int n=0,loop; 7 for(i=red;i<=black;i++) 8 for(j=red;j<=black;j++) 9 if(i!=j) 10 { 11 for(k=red;k<=black;k++) 12 { 13 if(k!=i&&k!=j) 14 { 15 n++; 16 printf("%-4d",n); 17 for(loop=1;loop<=3;loop++) 18 { 19 switch(loop) 20 { 21 case 1:pri=i;break; 22 case 2:pri=j;break; 23 case 3:pri=k;break; 24 default:break; 25 } 26 switch(pri) 27 { 28 case red:printf("%-10s","red");break; 29 case yellow:printf("%-10s","yellow");break; 30 case blue:printf("%-10s","blue");break; 31 case white:printf("%-10s","white");break; 32 case black:printf("%-10s","black");break; 33 default:break; 34 } 35 } 36 printf(" "); 37 } 38 } 39 } 40 printf(" total:%5d ",n); 41 return 0; 42 }
17-35行的分析过程如下:
1 /***************一般能想到的情况***************** 2 switch(i) 3 { 4 case red:printf("%-10s","red");break; 5 case yellow:printf("%-10s","yellow");break; 6 case blue:printf("%-10s","blue");break; 7 case white:printf("%-10s","white");break; 8 case black:printf("%-10s","black");break; 9 default:break; 10 } 11 switch(j) 12 { 13 case red:printf("%-10s","red");break; 14 case yellow:printf("%-10s","yellow");break; 15 case blue:printf("%-10s","blue");break; 16 case white:printf("%-10s","white");break; 17 case black:printf("%-10s","black");break; 18 default:break; 19 } 20 switch(k) 21 { 22 case red:printf("%-10s","red");break; 23 case yellow:printf("%-10s","yellow");break; 24 case blue:printf("%-10s","blue");break; 25 case white:printf("%-10s","white");break; 26 case black:printf("%-10s","black");break; 27 default:break; 28 } 29 ***************一般能想到的情况*****************/ 30 31 /**********************改进1******************** 32 33 34 将3段代码中不同的i,j,k用pri代替: 35 switch(pri) 36 { 37 case red:printf("%-10s","red");break; 38 case yellow:printf("%-10s","yellow");break; 39 case blue:printf("%-10s","blue");break; 40 case white:printf("%-10s","white");break; 41 case black:printf("%-10s","black");break; 42 default:break; 43 } 44 上段代码用CODE标识。 45 执行3次循环: 46 第1次:pri=i;CODE; 47 第2次:pri=j;CODE; 48 第3次:pri=k;CODE; 49 for(loop=1;loop<=3;loop++) 50 { if(loop==1) 51 pri=i; 52 else if(loop==2) 53 pri=j; 54 else if(loop=3) 55 pri=k; 56 CODE; 57 } 58 *********************改进1******************/ 59 60 /*********************最终版本*************** 61 62 63 64 再将if,else语句用switch改进: 65 for(loop=1;loop<=3;loop++) 66 { 67 switch(loop) 68 { 69 case 1:pri=i;break; 70 case 2:pri=j;break; 71 case 3:pri=k;break; 72 default:break; 73 } 74 CODE; 75 } 76 *********************最终版本****************/