【问题标题】:Is there a way to shorten the if else statements with switch?有没有办法用 switch 缩短 if else 语句?
【发布时间】:2019-10-18 17:15:11
【问题描述】:

我需要找到一种方法来缩短我的 if-else 语句与 switch。 if-else 语句真的很长,而且看起来很不专业,我希望有一种方法可以将它们缩短为几行,而不是像我现在拥有的那样混乱的多行。

我尝试实现一个 switch 块,但它并没有按照我想要的方式正确运行。

int numbers(int tal[]) {
int choice,a;
printf("\nWrite a specific number: ");
scanf("%d", &choice);
int b = 0;
for(a = 0 ;a < MAX ;a++){
    if(tal[a]== choice){
        b = 1;
        printf("\nExists in the sequence on this location: ");
        if(a <= 9)
        printf(" Row 1 och column %d\n",a +1);
        else if (a > 9 &&a <= 19)
        printf(" Row 2 och column %d\n", (a +1) - 10);
        else if (a > 19 &&a <= 29)
        printf(" Row 3 och column %d\n", (a +1) - 20);
        else if (a > 29 &&a <= 39)
        printf(" Row 4 och column %d\n", (a +1) - 30);
        else if (a > 39 &&a <= 49)
        printf(" Row 5 och column %d\n", (a +1) - 40);
        else if (a > 49 &&a <= 59)
        printf(" Row 6 och column %d\n", (a +1) - 50);
        else if (a > 59 &&a <= 69)
        printf(" Row 7 och column %d\n", (a +1) - 60);
        else if (a > 69 &&a <= 79)
        printf(" Row 8 och column %d\n", (a +1) - 70);
        else if (a > 79 &&a <= 89)
        printf(" Row 9 och column %d\n", (a +1) - 80);
        else if (a > 89 &&a <= 99)
        printf(" Row 10 och column %d\n", (a +1) - 90);
        break;
    }
}
if (b == 0)
    printf("\n%d It does not exists in the sequence", choice);
}

我让它工作了,我把所有的 if-else 语句都改成了这个; 编辑:nvm 我得到的列答案不正确。

int choice,a,row,col;
printf("\nWrite a specific number: ");
scanf("%d", &choice);
int b = 0;
for(a = 0 ;a < MAX ;a++){
    if(tal[a]== choice){
        b = 1;
        printf("\nExists in the sequence on this location: ");
        if(a <= 9)
       col = a % 10 + 1;
       row = a / 10 + 1;
       printf("Row %d och column %d\n", row, col);
        break;
    }
}
if (b == 0)
    printf("\n%d It does not exists in the sequence", choice);

enter image description here

【问题讨论】:

  • 有一种方法可以缩短这个时间,但不是switch,而是注意一些事情。例如,每个else if 中的第一个条件是多余的。但是,如果您看到模式并使用单个 printf 行和有点更复杂的算术表达式,则根本不需要整个条件。
  • 请不要通过从问题中删除必要信息来使现有答案无效。

标签: c if-statement switch-statement


【解决方案1】:

你可以通过以下方式让它看起来更好一点:

  • 正确缩进
  • 使用&gt; 省略冗余检查

像这样:

if(a <= 9)
    printf(" Row 1 och column %d\n",a +1);
else if (a <= 19)
    printf(" Row 2 och column %d\n", (a +1) - 10);
else if (a <= 29)
    printf(" Row 3 och column %d\n", (a +1) - 20);
...

但在这种情况下,您可以通过计算值来完全避免 if 块,例如:

col = a % 10 + 1;
row = a / 10 + 1;

print("Row %d och column %d\n", row, col);

【讨论】:

  • @maker 与您的原始解决方案相比,列计算有何不同?
  • 如果我选择一个位于最后一行和最后一列的数字,我应该得到的答案是该数字位于第 10 列和第 10 行,但我得到的答案是位于第 10 行第 0 列。
  • @maker a%10+1 不能永远为 a>0 的 0
  • 查看图片链接,你会看到我的基于控制台的程序,你可以清楚地看到它写出最后一个数字位于第0列。
  • 放弃if (a &lt;= 9),谁建议的?!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2020-11-17
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多