原文: https://www.programiz.com/cpp-programming/examples/calculator-switch-case
创建一个简单的计算器的示例,该计算器使用switch和break语句进行加,减,乘和除运算。
要理解此示例,您应该了解以下 C++ 编程主题:
该程序从用户处接收算术运算符(+,-,*,/)和两个操作数,并根据用户输入的运算符对这两个操作数执行运算。
示例:使用switch语句的简单计算器
# include <iostream>using namespace std;int main(){char op;float num1, num2;cout << "Enter operator either + or - or * or /: ";cin >> op;cout << "Enter two operands: ";cin >> num1 >> num2;switch(op){case '+':cout << num1+num2;break;case '-':cout << num1-num2;break;case '*':cout << num1*num2;break;case '/':cout << num1/num2;break;default:// If the operator is other than +, -, * or /, error message is showncout << "Error! operator is not correct";break;}return 0;}
输出
Enter operator either + or - or * or divide : -Enter two operands:3.48.43.4 - 8.4 = -5.0
该程序从用户那里获取一个运算符和两个操作数。
运算符存储在变量op中,两个操作数分别存储在num1和num2中。
然后,使用switch...case语句检查用户输入的运算符。
如果用户输入+,则执行case: '+'的语句并终止程序。
如果用户输入-,则执行case: '-'的语句并终止程序。
该程序对和/运算符的工作方式类似。 但是,如果运算符与四个字符[+,-,和/]中的任何一个都不匹配,则会执行默认语句,该语句显示错误消息。
