使用C++写一个计算器 要求在屏幕上录入numa +numb 回车 计算出结果 考虑分母不为零
时间: 2024-09-25 18:10:31 浏览: 40
在C++中编写一个简单的控制台计算器,你可以创建一个`Calculator`类,并提供加法操作。考虑到除数为零的情况,我们可以添加条件判断。以下是一个基础的实现:
```cpp
#include <iostream>
#include <stdexcept>
class Calculator {
public:
double add(double numerator, double denominator) {
if (denominator == 0) {
throw std::invalid_argument("Denominator cannot be zero");
}
return numerator / denominator;
}
// 主函数,用于接收用户输入并显示结果
void run() {
double numa, numb;
std::cout << "Enter the first number (numa): ";
std::cin >> numa;
std::cout << "Enter the second number (numb) and the denominator (separated by space): ";
std::cin >> numb >> denominator;
try {
double result = add(numa, numb);
std::cout << "The result of " << numa << " + (" << numb << "/" << denominator << ") is: " << result << "\n";
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << "\n";
}
}
};
int main() {
Calculator calculator;
calculator.run();
return 0;
}
阅读全文