C++ 简易计算器用函数实现
时间: 2023-11-14 20:32:01 浏览: 97
下面是使用函数实现的 C++ 简易计算器代码示例:
```cpp
#include <iostream>
using namespace std;
double add(double num1, double num2) {
return num1 + num2;
}
double subtract(double num1, double num2) {
return num1 - num2;
}
double multiply(double num1, double num2) {
return num1 * num2;
}
double divide(double num1, double num2) {
if (num2 == 0) {
cout << "Error! Division by zero" << endl;
exit(0);
}
return num1 / num2;
}
int main() {
char op;
double num1, num2, result;
cout << "Enter operator (+, -, *, /): ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
cout << "Error! Operator is not correct";
exit(0);
}
cout << num1 << " " << op << " " << num2 << " = " << result << endl;
return 0;
}
```
这段代码将加、减、乘、除操作封装成了四个函数,使代码更加模块化和可读性更高。同时,对除数为零的情况进行了处理,避免了程序崩溃。
阅读全文