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

C++ switch..case 语句

C++ switch..case 语句

在本教程中,我们将通过一些示例了解 switch 语句及其在 C++ 编程中的工作原理。

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

switch 的语法 C++中的语句是:

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;

    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}

switch 语句是如何工作的?

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

注意 :我们可以用 if...else..if 做同样的事情 梯子。但是,switch 的语法 语句更简洁,更易于阅读和编写。


switch语句流程图

<图>

示例:使用switch语句创建计算器

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

输出 1

Enter an operator (+, -, *, /): +
Enter two numbers: 
2.3
4.5
2.3 + 4.5 = 6.8

输出 2

Enter an operator (+, -, *, /): -
Enter two numbers: 
2.3
4.5
2.3 - 4.5 = -2.2

输出 3

Enter an operator (+, -, *, /): *
Enter two numbers: 
2.3
4.5
2.3 * 4.5 = 10.35

输出 4

Enter an operator (+, -, *, /): /
Enter two numbers: 
2.3
4.5
2.3 / 4.5 = 0.511111

输出 5

Enter an operator (+, -, *, /): ?
Enter two numbers: 
2.3
4.5
Error! The operator is not correct.

在上面的程序中,我们使用的是 switch...case 执行加减乘除的语句。

这个程序如何运作

  1. 我们首先提示用户输入所需的运算符。然后将此输入存储在 char 名为 oper 的变量 .
  2. 然后我们提示用户输入两个数字,它们存储在浮点变量num1中 和 num2 .
  3. switch 然后使用语句检查用户输入的运算符:
    • 如果用户输入+ , 对数字执行加法。
    • 如果用户输入- , 对数字执行减法。
    • 如果用户输入* , 对数字进行乘法运算。
    • 如果用户输入/ , 对数字进行除法。
    • 如果用户输入任何其他字符,则打印默认代码。

注意 break 语句在每个 case 中使用 堵塞。这将终止 switch 声明。

如果 break 不使用语句,正确的case之后的所有情况 被执行。


C语言

  1. C# switch 语句
  2. C# 中断语句
  3. C# continue 语句
  4. C++ 类型转换
  5. C++ 运算符
  6. C++ 注释
  7. C++ if, if...else 和嵌套 if...else
  8. C++ 中断语句
  9. C++ 继续语句
  10. C++ 函数
  11. C++ 数组
  12. 带有示例的 C++ Switch Case 语句