C++ 中的 switch case 语句


2022年8月17日, Learn eTutorial
1877

在本教程中,让我们讨论 C++ 支持的 switch 语句,用于处理决策制定

switch 语句允许我们在执行代码块的多个选项之间进行选择。

switch 语句检查变量是否与一系列值相等。每个值称为一个 case,每个 case 检查正在切换的变量。

C++ 中的 switch 语句具有以下语法


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

    case constant2:
        // here the code will be executed only if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // here the code will be executed only if 
        //here the  expression are not having a match with any constant
}
 

C++ 中 switch 语句的工作原理

表达式将只计算一次,然后将结果与每个 case 标签的结果进行比较。

假设,如果找到匹配项,则将执行与匹配标签后面的代码。例如,如果变量的值是 constant2,则将执行 case constant2: 后面的代码,直到遇到 break 语句。

如果找不到匹配项,则将执行 default 后面的代码。

switch 语句流程图

Switch control flowchart

C++ 中 switch 语句的示例

使用 switch 语句,让我们创建一个计算器


#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << " An operator should be entered (+, -, *, /): ";
    cin >> oper;
    cout << "Please 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 doesn't match with any case constant (+, -, *, /)
            cout << "Error obtained! The operator is incorrect";
            break;
    }

    return 0;
}

输出


Output 1
An operator should be entered (+, -, *, /): +
Please enter two numbers: 
20
50
20 + 50 = 70

Output 2
An operator should be entered (+, -, *, /): -
Please enter two numbers: 
9
19
9 - 19 = -10

Output 3
An operator should be entered (+, -, *, /): *
Please enter two numbers: 
7
2
7 * 2 = 14

Output 4
An operator should be entered (+, -, *, /): /
Please enter two numbers: 
10
5
10 / 5 = 2

Output 5
An operator should be entered (+, -, *, /): ?
Please enter two numbers: 
2
3
Error obtained! The operator is incorrect

在前面的程序中,使用 switch...case 语句执行加法、减法、乘法和除法。

对上述程序的分析

  1. 我们首先要求用户输入所需的运算符。然后使用名为 oper 的 char 变量来存储此输入。
  2. 然后提示用户输入两个数字,这些数字保存在 float 变量 num1 和 num2 中。
  3. 然后使用 switch 语句来验证用户输入的运算符
    • 当用户输入 + 时,将相加。
    • 当用户输入 - 时,将相减。
    • 如果用户输入 *,则执行乘法。
    • 当用户输入 / 时,将相除。
    • 如果用户输入其他字符,则打印 default 代码。
  4. break 语句在每个 case 块中使用。这会结束 switch 语句。
  5. 如果没有 break 语句,则将执行正确 case 后面的所有 case。