switch语句的使用,非常好

时间:2024-08-18 22:35:32

这是谭浩强课本上枚举类型的例子,但是我贴这个例子的代码不是因为枚举类型,是因为这个代码使用switch语句用得非常好,值得一贴。

题目是这样的:有红、黄、蓝、白、黑5中颜色的球若干,依次取出3个球,求3个球为不同颜色时的排列方式。

 #include<stdio.h>

 int main(){
enum color {red,yellow,blue,white,black};
enum color i,j,k,pri;
int n=,loop;
for(i=red;i<=black;i++)
for(j=red;j<=black;j++)
if(i!=j)
{
for(k=red;k<=black;k++)
{
if(k!=i&&k!=j)
{
n++;
printf("%-4d",n);
for(loop=;loop<=;loop++)
{
switch(loop)
{
case :pri=i;break;
case :pri=j;break;
case :pri=k;break;
default:break;
}
switch(pri)
{
case red:printf("%-10s","red");break;
case yellow:printf("%-10s","yellow");break;
case blue:printf("%-10s","blue");break;
case white:printf("%-10s","white");break;
case black:printf("%-10s","black");break;
default:break;
}
}
printf("\n");
}
}
}
printf("\ntotal:%5d\n",n);
return ;
}

17-35行的分析过程如下:

 /***************一般能想到的情况*****************
switch(i)
{
case red:printf("%-10s","red");break;
case yellow:printf("%-10s","yellow");break;
case blue:printf("%-10s","blue");break;
case white:printf("%-10s","white");break;
case black:printf("%-10s","black");break;
default:break;
}
switch(j)
{
case red:printf("%-10s","red");break;
case yellow:printf("%-10s","yellow");break;
case blue:printf("%-10s","blue");break;
case white:printf("%-10s","white");break;
case black:printf("%-10s","black");break;
default:break;
}
switch(k)
{
case red:printf("%-10s","red");break;
case yellow:printf("%-10s","yellow");break;
case blue:printf("%-10s","blue");break;
case white:printf("%-10s","white");break;
case black:printf("%-10s","black");break;
default:break;
}
***************一般能想到的情况*****************/ /**********************改进1******************** 将3段代码中不同的i,j,k用pri代替:
switch(pri)
{
case red:printf("%-10s","red");break;
case yellow:printf("%-10s","yellow");break;
case blue:printf("%-10s","blue");break;
case white:printf("%-10s","white");break;
case black:printf("%-10s","black");break;
default:break;
}
上段代码用CODE标识。
执行3次循环:
第1次:pri=i;CODE;
第2次:pri=j;CODE;
第3次:pri=k;CODE;
for(loop=1;loop<=3;loop++)
{ if(loop==1)
pri=i;
else if(loop==2)
pri=j;
else if(loop=3)
pri=k;
CODE;
}
*********************改进1******************/ /*********************最终版本*************** 再将if,else语句用switch改进:
for(loop=1;loop<=3;loop++)
{
switch(loop)
{
case 1:pri=i;break;
case 2:pri=j;break;
case 3:pri=k;break;
default:break;
}
CODE;
}
*********************最终版本****************/