switch
语句根据整数表达式的结果从一组可能的操作中选择相应操作。switch
语句的一般方法如下:
switch(integer_expression)
{
case constant_expression_1:
statements_1;
break;
....
case constant_expression_n:
statements_n;
break;
default:
statements;
break;
}
因为枚举类型是整数类型,所以可以使用枚举类型的变量来控制开关。
示例代码
#include <stdio.h>
int main()
{
enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
enum Weekday today = Wednesday;
switch (today)
{
case Sunday:
printf("今天是星期日.\n");
break;
case Monday:
printf("今天是星期一.\n");
break;
case Tuesday:
printf("今天是星期二.\n");
break;
case Wednesday:
printf("今天是星期三.\n");
break;
case Thursday:
printf("今天是星期四.\n");
break;
case Friday:
printf("今天是星期五.\n");
break;
case Saturday:
printf("今天是星期六.\n");
break;
}
return 0;
}
执行上面示例代码,得到以下结果:
hema@ubuntu:~/book$ gcc main.c
hema@ubuntu:~/book$ ./a.out
今天是星期三.
因为枚举类型是整数类型,所以可以使用枚举类型的变量来控制开关。
示例
使用switch
语句实现一个简单的计算器,参考以下代码:
#include <stdio.h>
int main(void)
{
double number1 = 0.0;
double number2 = 0.0;
char operation = 0; // 仅支持: +, -, *, / 和 % 运算符
printf("输入计算表达式(仅支持: +, -, *, /) => ");
scanf("%lf %c %lf", &number1, &operation, &number2);
switch (operation)
{
case '+':
printf("%lf + %lf = %lf\n", number1, number2, number1 + number2);
break;
case '-':
printf("%lf - %lf = %lf\n", number1, number2, number1 - number2);
break;
case '*':
printf("%lf x %lf = %lf\n", number1, number2, number1 * number2);
break;
case '/':
if (number2 == 0)// 检查第二个操作数是否为零
printf("\n\n 除数不能为0!\n");
else
printf("%lf / %lf = %lf\n", number1, number2, number1 / number2);
break;
case '%': // 检查第二个操作数是否为零
if ((long)number2 == 0)
printf("\n\n 除数不能为0!\n");
else
printf("%lf \% %lf = %ld\n", number1, number2, (long)number1 % (long)number2);
break;
default:
printf("\n\n 非法操作!\n");
break;
}
return 0;
}
执行上面示例代码,得到以下结果:
hema@ubuntu:~/book$ gcc main.c
hema@ubuntu:~/book$ ./a.out
输入计算表达式(仅支持: +, -, *, /) => 11 + 22
11.000000 + 22.000000 = 33.000000