C switch 语句
本文中,我们通过示例介绍 C 语言中的 switch 语句以及详细的用法。
在 C 语言中,switch
语句用来处理多个分支的情况,根据当前对应的值执行对应的 case
块。
你可以用 if...else..if
梯子做同样的事情。但是, switch
语句的语法更易于阅读和编写。
switch…case 的语法
switch (expression)
{
case constant1:
// 代码
break;
case constant2:
// 代码
break;
.
.
.
default:
// default statements
}
switch 语句说明:
expression
被评估一次并与每个 case
中的值进行比较。
- 如果匹配,则执行匹配
case
后的相应语句,直到遇到break
。 - 如果不匹配,则执行默认语句。
如果我们不在每个 case
中使用 break
,则执行匹配 case
之后的所有语句。
顺便说一句, switch
语句内的 default
子句是可选的。
switch 语句流程图
示例:简单计算器
// Program to create a simple calculator
#include <stdio.h>
int main() {
char operator;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
输出
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
在程序中,用户输入的运算符存储在 operator
变量中。并且,两个操作数分别存储在 n1
和 n2
变量中。
由于用户输入的运算符是 -
,因此程序的控制跳转到:
printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);
执行完上面的语句后,break
语句终止此 switch
语句。