在本教程中,让我们讨论 C++ 支持的 switch 语句,用于处理决策制定。
switch 语句允许我们在执行代码块的多个选项之间进行选择。
switch 语句检查变量是否与一系列值相等。每个值称为一个 case,每个 case 检查正在切换的变量。
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
}
表达式将只计算一次,然后将结果与每个 case 标签的结果进行比较。
假设,如果找到匹配项,则将执行与匹配标签后面的代码。例如,如果变量的值是 constant2,则将执行 case constant2: 后面的代码,直到遇到 break 语句。
如果找不到匹配项,则将执行 default 后面的代码。

使用 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 语句执行加法、减法、乘法和除法。