编写一个计算器的C++类,能够完成两个数的求和、相乘、相除,开根号、平方功能。
时间: 2024-09-15 10:09:41 浏览: 76
可以创建一个名为`Calculator`的C++类,这个类会包含私有成员变量以及公有成员函数来实现所需的操作。以下是简单的类设计:
```cpp
#include <iostream>
#include <cmath> // 包含数学库,用于计算根号和平方
class Calculator {
private:
double num1;
double num2;
public:
// 构造函数,初始化两个数字
Calculator(double a = 0, double b = 0) : num1(a), num2(b) {}
// 求和
double add() const { return num1 + num2; }
// 相乘
double multiply() const { return num1 * num2; }
// 相除 (处理除数为零的情况)
double divide(double divisor) const {
if (divisor != 0) {
return num1 / divisor;
} else {
throw std::runtime_error("Division by zero is not allowed.");
}
}
// 开根号
double square_root() const {
if (num1 >= 0) {
return sqrt(num1);
} else {
throw std::runtime_error("Square root of negative number is undefined.");
}
}
// 平方
double square() const { return num1 * num1; }
// 显示结果的友元函数,方便外部获取计算结果
friend std::ostream& operator<<(std::ostream& os, const Calculator& calc);
};
// 输出运算结果到流
std::ostream& operator<<(std::ostream& os, const Calculator& calc) {
os << "Result for operation: ";
os << "Sum: " << calc.add() << "\n";
os << "Product: " << calc.multiply() << "\n";
try {
os << "Quotient: " << calc.divide(2) << "\n"; // 示例除以2
} catch (const std::exception& e) {
os << e.what() << "\n";
}
os << "Square Root: " << calc.square_root() << "\n";
os << "Square: " << calc.square() << "\n";
return os;
}
int main() {
Calculator calculator(5, 3);
std::cout << calculator << std::endl;
return 0;
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![exe](https://img-home.csdnimg.cn/images/20241231044909.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)