if 語句只能處理二選一的情況,當需要實現多種可能之一時,若使用多重 if...else if 或嵌套 if,程式碼會變得冗長且可讀性降低。C 語言提供了 switch 開關語句專門處理多路分支,使程式更簡潔。
switch (表達式) {
case 常量表達式1: 語句序列1; break;
case 常量表達式2: 語句序列2; break;
...
case 常量表達式n: 語句n; break;
default: 語句n+1;
}
其中常量表達式的值必須是整型、字符型或枚舉類型。各語句序列允許有多條語句,不需用大括號括起。若某 case 的語句序列為空,對應的 break 可省略。
當多個 case 需執行相同語句時,可堆疊 case 標籤:
switch(i) {
case 1:
case 2:
case 3: 語句1; break;
case 4:
case 5: 語句2; break;
default: 語句3;
}
當 i 為 1、2 或 3 時執行語句1;為 4 或 5 時執行語句2;否則執行語句3。
#include <stdio.h>
int main() {
int month, day;
printf("please input the month number: ");
scanf("%d", &month);
switch(month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
day = 31; break;
case 4: case 6: case 9: case 11:
day = 30; break;
case 2:
day = 28; break;
default:
day = -1;
}
if (day == -1)
printf("Invalid month input!\n");
else
printf("1999.%d has %d days\n", month, day);
return 0;
}
使用嵌套 if 處理各種係數情況:
#include <math.h>
#include <stdio.h>
int main() {
float a, b, c, s, x1, x2;
double t;
printf("please input a,b,c: ");
scanf("%f%f%f", &a, &b, &c);
if (a == 0.0) {
if (b != 0.0)
printf("the root is: %f\n", -c/b);
else if (c == 0.0)
printf("x is inexactive\n");
else
printf("no root!\n");
} else {
s = b*b - 4*a*c;
if (s >= 0.0) {
if (s > 0.0) {
t = sqrt(s);
x1 = (-b + t) / (2*a);
x2 = (-b - t) / (2*a);
printf("There are two different roots: %f and %f\n", x1, x2);
} else {
printf("There are two equal roots: %f\n", -b/(2*a));
}
} else {
t = sqrt(-s);
x1 = -b / (2*a); // 實部
x2 = fabs(t / (2*a)); // 虛部絕對值
printf("There are two virtual roots:\n");
printf("%f + i%f\t%f - i%f\n", x1, x2, x1, x2);
}
}
return 0;
}
RUN
please input a,b,c: 1 2 3
There are two virtual roots:
-1.000000 + i1.000000 -1.000000 - i1.000000
RUN
please input a,b,c: 2 5 3
There are two different roots: -1.000000 and -1.500000
RUN
please input a,b,c: 0 0 3
No root!