亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C switch 语句

C switch 语句

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

switch 语句允许我们在许多备选方案中执行一个代码块。

你可以用 if...else..if 做同样的事情 梯子。但是,switch 的语法 语句更容易读写。


switch...case的语法

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

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

switch 语句是如何工作的?

表达式 评估一次并与每个 case 的值进行比较 标签。

注意事项:


switch语句流程图

<图>

示例:简单计算器

// Program to create a simple calculator
#include <stdio.h>

int main() {
    char operation;
    double n1, n2;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operation);
    printf("Enter two operands: ");
    scanf("%lf %lf",&n1, &n2);

    switch(operation)
    {
        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 存储在变量 n1 中 和 n2 分别。

由于操作- ,程序的控制跳转到

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

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


C语言

  1. 带开关的电路
  2. 换向二极管
  3. 开关类型
  4. 联系“Bounce”
  5. 万用表
  6. C# switch 语句
  7. C# 中断语句
  8. C# continue 语句
  9. C++ 中断语句
  10. C++ switch..case 语句
  11. 带有示例的 C++ Switch Case 语句
  12. C - 基本语法