c++自定义函数简单计算器
时间: 2024-11-29 10:14:26 浏览: 15
在C++中,你可以创建一个简单的函数来实现一个计算器功能,比如加、减、乘、除操作。下面是一个基础示例,它包含一个`Calculator`类,其中定义了四个基本运算的方法:
```cpp
#include <iostream>
class Calculator {
public:
// 加法
int add(int a, int b) { return a + b; }
// 减法
int subtract(int a, int b) { return a - b; }
// 乘法
int multiply(int a, int b) { return a * b; }
// 除法(注意处理除数为0的情况)
int divide(int a, int b) {
if (b != 0) {
return a / b;
} else {
std::cerr << "Error: Division by zero is not allowed.\n";
return 0;
}
}
};
int main() {
Calculator calc;
int num1, num2;
char operation;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter an operator (+, -, *, /): ";
std::cin >> operation;
std::cout << "Enter second number: ";
std::cin >> num2;
switch(operation) {
case '+':
std::cout << "Result: " << calc.add(num1, num2) << "\n";
break;
case '-':
std::cout << "Result: " << calc.subtract(num1, num2) << "\n";
break;
case '*':
std::cout << "Result: " << calc.multiply(num1, num2) << "\n";
break;
case '/':
std::cout << "Result: " << calc.divide(num1, num2) << "\n";
break;
default:
std::cerr << "Invalid operator. Please use +, -, *, or /\n";
}
return 0;
}
```
阅读全文