C++用switch语句编写一个简单的实数四则运算程序
时间: 2024-11-18 13:27:33 浏览: 3
四则运算 程序 , vc++ 6.0 编辑
在C++中,你可以使用`switch`语句结合`enum`来编写一个简单的实数四则运算程序。首先,你需要创建一个枚举来表示运算符,并定义对应的函数。这里是一个示例:
```cpp
#include <iostream>
using namespace std;
// 定义运算符枚举
enum Operation {
ADD,
SUBTRACT,
MULTIPLY,
DIVIDE
};
// 根据运算符执行相应的操作
double applyOperation(double num1, double num2, Operation op) {
switch (op) {
case ADD:
return num1 + num2;
case SUBTRACT:
return num1 - num2;
case MULTIPLY:
return num1 * num2;
case DIVIDE:
if (num2 != 0) // 防止除零错误
return num1 / num2;
else
throw "Error: Division by zero is not allowed!";
default:
throw "Invalid operation"; // 如果输入了无效的运算符
}
}
int main() {
double num1, num2;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Choose an operation (+, -, *, /): ";
char choice;
cin >> choice;
Operation op;
switch(choice) {
case '+':
op = ADD;
break;
case '-':
op = SUBTRACT;
break;
case '*':
op = MULTIPLY;
break;
case '/':
op = DIVIDE;
break;
default:
cout << "Invalid input! Please choose a valid operator." << endl;
return 1; // 结束程序并返回错误码
}
try {
double result = applyOperation(num1, num2, op);
cout << "Result of the operation is: " << result << endl;
} catch(const char* msg) {
cerr << msg << endl;
}
return 0;
}
```
阅读全文