📜  C开关声明

📅  最后修改于: 2020-10-04 12:30:06             🧑  作者: Mango

在本教程中,您将借助示例学习在C编程中创建switch语句。

switch语句使我们可以在许多选择中执行一个代码块。

您可以使用if...else..if梯子执行相同的if...else..if 。但是, switch语句的语法更容易读写。


switch … case的语法

switch (expression)
​{
    case constant1:
      // statements
      break;

    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

switch语句如何工作?

表达式将被评估一次,并与每个案例标签的值进行比较。

  • 如果匹配,则执行匹配标签后的相应语句。例如,如果表达式的值等于constant2 ,则在case constant2:之后执行语句,直到遇到break
  • 如果不匹配,则执行默认语句。

如果不使用break ,则匹配标签后的所有语句都将执行。

顺便说一句, switch语句中的default子句是可选的。


切换语句流程图

Flowchart of switch statement


示例:简单计算器

// Program to create a simple calculator
#include 

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

用户输入的 运算符存储在运算符变量中。并且,两个操作数32.512.4分别存储在变量n1n2中

由于运算符- ,因此程序的控制跳转至

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

最后,break语句终止switch语句。