请用C++语言,编写一个具有四则运算计算器功能的程序
时间: 2024-10-09 12:11:51 浏览: 42
在C++中,你可以创建一个简单的命令行四则运算计算器。这里是一个基础的示例,使用结构体和函数实现:
```cpp
#include <iostream>
using namespace std;
// 定义运算符和操作数的数据结构
struct Calculator {
double num1, num2;
char operator_; // 运算符
};
// 函数来处理加法、减法、乘法和除法
double performOperation(Calculator calc) {
switch (calc.operator_) {
case '+':
return calc.num1 + calc.num2;
case '-':
return calc.num1 - calc.num2;
case '*':
return calc.num1 * calc.num2;
case '/':
if (calc.num2 != 0) // 防止除数为零错误
return calc.num1 / calc.num2;
else
throw "Error: Division by zero!";
default:
throw "Error: Invalid operator!";
}
}
int main() {
double num1, num2;
char op;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Choose an operation (+, -, *, /): ";
cin >> op;
Calculator calc = {num1, num2, op};
try {
double result = performOperation(calc);
cout << "Result: " << result << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
```
阅读全文