C – 具有多个案例编号的开关

所以我的教授要求我们创建一个switch语句。 我们只允许使用“SWITCH”语句来执行该程序。 他希望我们输入一个数字然后显示它,如果它在数字范围内,将显示如下所示的公文包编号。 现在……我知道对于这种类型的程序,使用IF语句更容易。 做案例1:案例2:案例3 ……案例30将起作用但由于数字范围将花费太多时间。

#include  main() { int x; char ch1; printf("Enter a number: "); scanf("%d",&x); switch(x) { case 1://for the first case #1-30 case 30: printf("The number you entered is >= 1 and = 31 and = 60 and = 90 and <= 100"); printf("\nTake Briefcase Number 4"); break; default: printf("Not in the number range"); break; } getch(); } 

我的教授告诉我们,如何做到这一点有一个较短的方法,但不会告诉我们如何做。 我能想到缩短它的唯一方法是使用IF,但我们不允许这样做。 关于如何使这项工作成功的任何想法?

使用GCC和CLang,您可以使用案例范围,如下所示:

 switch (x){ case 1 ... 30: printf ("The number you entered is >= 1 and <= 30\n"); break; } 

唯一的交叉编译器解决方案是使用这样的case语句:

 switch (x){ case 1: case 2: case 3: case 4: case 5: case 6: printf ("The number you entered is >= 1 and <= 6\n"); break; } 

编辑:使用某些东西来实现switch (x / 10)是另一种好方法。 当范围不是10差异时,使用GCC案例范围可能更简单,但另一方面,您的教授可能不会将GCC扩展作为答案。

如果范围一致,那么您可以丢弃一些数据:

 switch (x / 10 ) { case 0: case 1: case 2: // x is 0 - 29 break ; // etc ... } 

否则你将不得不在边缘做一些hackery。

  Try this ... #include  #include  main() { int x; char ch1; printf("Enter a number: "); scanf("%d",&x); int y=ceil(x/30.0); switch(y) { case 1: printf("The number you entered is >= 1 and <= 30"); printf("\nTake Briefcase Number 1"); break; case 2: printf("The number you entered is >= 31 and <= 60"); printf("\nTake Briefcase Number 2"); break; case 3: printf("The number you entered is >= 61 and <= 90"); printf("\nTake Briefcase Number 3"); break; case 4: printf("The number you entered is >= 91 and <= 100"); printf("\nTake Briefcase Number 4"); break; default: printf("Not in the number range"); break; } getch(); }