此程序从用户那里获取一个算术运算符(+、-、*、/)和两个操作数,并根据用户输入的运算符对这两个操作数执行运算。
示例:使用 switch 语句的简易计算器
# include <iostream>
using namespace std;
int main() {
char op;
float num1, num2;
cout << "Enter operator: +, -, *, /: ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op) {
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:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
}
return 0;
}
输出
Enter operator: +, -, *, /: - Enter two operands: 3.4 8.4 3.4 - 8.4 = -5
此程序从用户那里获取运算符和两个操作数。
运算符存储在变量 op 中,两个操作数分别存储在 num1 和 num2 中。
然后,使用 switch...case
语句来检查用户输入的运算符。
如果用户输入 +
,则执行 case: '+'
的语句,程序终止。
如果用户输入 -
,则执行 case: '-'
的语句,程序终止。
此程序对 *
和 /
运算符的工作方式类似。但是,如果运算符与四个字符 [ +, -, * 和 / ] 中的任何一个都不匹配,则执行 default
语句,该语句会显示错误消息。
另请阅读