加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C – 多个案例编号切换

发布时间:2020-12-16 05:43:33 所属栏目:百科 来源:网络整理
导读:所以我的教授要求我们创建一个switch语句.我们被允许仅使用“SWITCH”语句来执行程序.他希望我们输入一个数字,然后在数字范围内显示,并显示如下所示的公文包编号.现在…我知道对于这种类型的程序,使用IF语句更容易.案例1:案例2:案例3 …案例30将工作,但由
所以我的教授要求我们创建一个switch语句.我们被允许仅使用“SWITCH”语句来执行程序.他希望我们输入一个数字,然后在数字范围内显示,并显示如下所示的公文包编号.现在…我知道对于这种类型的程序,使用IF语句更容易.案例1:案例2:案例3 …案例30将工作,但由于数字范围将花费太多时间.
#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,但我们不允许.任何关于我如何使这项工作的想法?

解决方法

使用GCC和CLang,您可以使用大小写范围,如下所示:
switch (x){

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

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

switch (x){

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

编辑:使用某种功能来切换(x / 10)是另一个很好的方法.当范围不是10的差异时,使用GCC案例范围可能更简单,但另一方面,您的教授可能不会将GCC扩展名作为答案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读