有没有办法用switch缩短if else语句?

时间:2019-10-18 17:15:11

标签: c if-statement switch-statement

我需要找到一种方法来使用switch缩短if-else语句。 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

1 个答案:

答案 0 :(得分:7)

您可以通过以下方法使它看起来更好一点:

  • 正确缩进
  • 使用>省略冗余检查

那样:

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);