用c++写出包含加减乘除运算的计算器
时间: 2024-12-12 09:29:39 浏览: 8
在C++中,我们可以创建一个简单的控制台计算器程序,它包含基本的加、减、乘、除操作。下面是一个基础版本的示例:
```cpp
#include <iostream>
class Calculator {
public:
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
std::cerr << "Error: Division by zero is not allowed." << std::endl;
return 0; // 返回一个默认值或抛出异常
}
}
};
int main() {
Calculator calc;
double num1, num2;
char operation;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter operator (+, -, *, /): ";
std::cin >> operation;
std::cout << "Enter second number: ";
std::cin >> num2;
switch(operation) {
case '+':
std::cout << "Result: " << calc.add(num1, num2) << std::endl;
break;
case '-':
std::cout << "Result: " << calc.subtract(num1, num2) << std::endl;
break;
case '*':
std::cout << "Result: " << calc.multiply(num1, num2) << std::endl;
break;
case '/':
std::cout << "Result: " << calc.divide(num1, num2) << std::endl;
break;
default:
std::cerr << "Invalid operator. Please use one of the supported operators." << std::endl;
break;
}
return 0;
}
```
在这个程序中,我们首先定义了一个`Calculator`类,包含了四个方法对应四种基本运算。然后在`main`函数中,用户输入两个数字和一个运算符,根据运算符选择相应的方法进行计算。
阅读全文