C-切换多个案例编号 [英] C - Switch with multiple case numbers
问题描述
因此,我的教授要求我们创建一个转换语句.我们只允许使用"SWITCH" 语句来执行该程序.他希望我们输入一个数字,然后显示它(如果它在数字范围内),并将显示哪个公文包数字,如下所示.现在...我知道,对于这种类型的程序,使用 IF语句更容易.进行案例1:案例2:案例3 ...案例30可以使用,但由于数量范围,将花费太多时间.
So my professor asked us to create a switch statement. We are allowed to use only the "SWITCH" statement to do the program. He wants us to input a number and then display it if it is on the number range and what briefcase number will be taken as shown below. Now... I know that for this type of program it is easier to use the IF statement. Doing Case 1: Case 2: Case 3...Case 30 will work but will take too much time due to the number range.
#include <stdio.h>
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 <= 30");
printf("\nTake Briefcase Number 1");
break;
case 31://for the second case #31-59
case 59:
printf("The number you entered is >= 31 and <= 59");
printf("\nTake Briefcase Number 2");
break;
case 60://for the third case #60-89
case 89:
printf("The number you entered is >= 60 and <= 89");
printf("\nTake Briefcase Number 3");
break;
case 90://for the fourth case #90-100
case 100:
printf("The number you entered is >= 90 and <= 100");
printf("\nTake Briefcase Number 4");
break;
default:
printf("Not in the number range");
break;
}
getch();
}
我的教授告诉我们,这样做的方法更短,但是不会告诉我们如何做.我想缩短它的唯一方法是使用IF,但我们不允许这样做.关于如何解决这个问题有什么想法吗?
My professor told us that there is a shorter way on how to do this but won't tell us how. The only way I can think of shortening it is by using IF but we are not allowed to. Any Ideas on how I can make this work out?
推荐答案
借助GCC和CLang,您可以使用大小写范围,如下所示:
With GCC and CLang, you can use case ranges, like this:
switch (x){
case 1 ... 30:
printf ("The number you entered is >= 1 and <= 30\n");
break;
}
唯一的交叉编译器解决方案是使用这样的case语句:
The only cross-compiler solution is to use case statements like this:
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扩展名作为答案.
Using something to the effect of switch (x / 10)
is another good way of doing this. It may be simpler to use GCC case ranges when the ranges aren't differences of 10
, but on the other hand your professor might not take a GCC extension as an answer.
这篇关于C-切换多个案例编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!