该程序从用户那里获取一个算术运算符(+、-、*、/)和两个操作数,并根据用户输入的运算符对这两个操作数执行运算。
示例: 使用 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 either + or-or * or divide :-
Enter two operands: 3.4 8.4
3.4-8.4 =-5.0
这个程序从用户那里获取一个运算符和两个操作数。
运算符存储在变量
op中,两个操作数分别存储在
num1和
num2中。
然后,switch...case 语句用于检查用户输入的运算符。
如果用户输入+,则执行
case: '+'
的语句并终止程序。
如果用户输入-那么,
case: '-'
的语句被执行并终止程序。
这个程序对于 * 和/操作符的工作方式类似。但是,如果运算符不匹配四个字符 [+、-、* 和/] 中的任何一个,则执行 default 语句并显示错误消息。