c++可进行四则运算的程序
时间: 2024-10-01 22:10:23 浏览: 27
小学生四则运算练习系统(C++实现)
5星 · 资源好评率100%
在C++中,编写一个简单的四则运算程序,你可以创建一个包含加法、减法、乘法和除法函数的类,并提供一个用户界面让使用者输入操作数和选择运算符。下面是一个基础的示例:
```cpp
#include <iostream>
using namespace std;
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
throw "Error: Division by zero is not allowed!";
}
void performOperation() {
double num1, num2;
char operatorChoice;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Choose an operation (+, -, *, /): ";
cin >> operatorChoice;
switch (operatorChoice) {
case '+':
cout << "Result: " << add(num1, num2) << endl;
break;
case '-':
cout << "Result: " << subtract(num1, num2) << endl;
break;
case '*':
cout << "Result: " << multiply(num1, num2) << endl;
break;
case '/':
try {
cout << "Result: " << divide(num1, num2) << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
break;
default:
cerr << "Invalid choice! Please enter a valid operator." << endl;
break;
}
}
};
int main() {
Calculator calc;
calc.performOperation();
return 0;
}
```
阅读全文