原文: https://www.programiz.com/c-programming/c-switch-case-statement
在本教程中,您将通过一个示例学习在 C 编程中创建switch语句。
switch语句使我们可以执行许多替代方案中的一个代码块。
您可以使用if...else..if梯形图执行相同的操作。 但是,switch语句的语法更容易读写。
switch...case的语法
switch (expression){case constant1:// statementsbreak;case constant2:// statementsbreak;...default:// default statements}
switch语句如何工作?
对expression进行一次求值,并与每个case标签的值进行比较。
- 如果匹配,则执行匹配标签后的相应语句。 例如,如果表达式的值等于
constant2,则执行case constant2:之后的语句,直到遇到break。 - 如果不匹配,则执行默认语句。
如果我们不使用break,则执行匹配标签之后的所有语句。
顺便说一下,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.512.432.5 - 12.4 = 20.1
用户输入的-运算符存储在operator变量中。 并且,两个操作数32.5和12.4分别存储在变量n1和n2中。
由于operator为-,因此程序控制跳至
printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);
最后, break语句终止switch语句。
