📅  最后修改于: 2020-09-25 05:13:17             🧑  作者: Mango
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
语句的语法更简洁,更易于读写。
// 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
。