使用 switch...case 制作一个简单的计算器来加、减、乘或除的 C++ 程序
要理解此示例,您应该具备以下 C++ 编程 主题的知识:
该程序从用户处获取算术运算符(+
、-
、*
、/
)和两个操作数,并根据用户输入的运算符对这两个操作数执行运算。
示例:使用 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
和 num1
中。
然后,switch...case
语句用于检查用户输入的运算符。
如果用户输入 +
, 则执行 case: '+'
语句并终止程序。
如果用户输入 -
则执行 case: '-'
语句并终止程序。
_
和 /
运算符的工作方式类似。但是,如果运算符不匹配四个字符(+
、-
、*
、/
)中的任何一个,则执行 default
语句并显示错误消息。