mak*_*ker 2 c if-statement switch-statement
我需要找到一种方法来使用switch缩短我的if-else语句。if-else语句很长,看起来真的很不专业,我希望有一种方法可以将它们缩短为几行,而不是像我现在看到的那样多行。
我尝试实现一个开关块,但是开关没有正确地按我希望的方式运行。
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);
}
Run Code Online (Sandbox Code Playgroud)
我使它起作用,并且将所有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);
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方法使它看起来更好一点:
>
像那样:
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);
...
Run Code Online (Sandbox Code Playgroud)
但是在这种情况下,您可以通过计算值来完全避免if块,例如:
col = a % 10 + 1;
row = a / 10 + 1;
print("Row %d och column %d\n", row, col);
Run Code Online (Sandbox Code Playgroud)