📜  C++ switch..case语句

📅  最后修改于: 2020-09-25 05:13:17             🧑  作者: Mango

在本教程中,我们将借助一些示例来学习switch语句及其在C++编程中的工作。

switch语句使我们可以执行许多替代方案中的代码块。

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

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梯子执行相同的if...else..if 。但是, switch语句的语法更简洁,更易于读写。

开关流程图

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

// Program to build a simple calculator using switch Statement
#include 
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语句执行加法,减法,乘法和除法。

该程序如何运作

注意,在每个case块内都使用break语句。这将终止switch语句。

如果不使用break语句,则执行正确case之后的所有case