所以我的教授要求我們創建一個switch語句。我們被允許使用只有「SWITCH」聲明來執行該程序。他希望我們輸入一個數字,然後在數字範圍內顯示,然後如下所示輸入公文包號碼。現在...我知道這種類型的程序更容易使用IF語句。做案例1:案例2:案例3 ...案例30將工作,但由於數量範圍,將花費太多時間。C - 多個案例號的開關
#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,但我們不允許。任何想法,我如何可以使這項工作?
只是爲了檢查,你確定第一個案件從1到30?而不是1到29? –
您是否在考慮'案例1:案例30:'會匹配範圍內的任何數字?它不會。 – John3136
您的第一對'case'標籤只能找到2個值:1和30;他們忽略2..29。對於下一個「範圍」也是如此,等等。只使用開關,你就會感受到一個痛苦的世界。 –