分别定义四个函数,求两个整数的和,差,积商。在main()函数中输入两个整数和运算符,根据用户输入的运算符调用对应的函数,并将结果输出,要求结果保留两位小数
时间: 2024-02-03 10:12:36 浏览: 22
下面是代码实现:
```c++
#include <iostream>
#include <iomanip> //用于设置输出精度
using namespace std;
float add(int a, int b) {
return a + b;
}
float subtract(int a, int b) {
return a - b;
}
float multiply(int a, int b) {
return a * b;
}
float divide(int a, int b) {
if (b == 0) {
cout << "Error: divided by zero!" << endl; //处理除数为0的情况
return 0;
}
return (float)a / b; //强制转换为浮点数
}
int main() {
int a, b;
char op; //运算符
cout << "Please input two integers and an operator (+, -, *, /): ";
cin >> a >> b >> op;
float result;
switch (op) {
case '+':
result = add(a, b);
break;
case '-':
result = subtract(a, b);
break;
case '*':
result = multiply(a, b);
break;
case '/':
result = divide(a, b);
break;
default:
cout << "Invalid operator!" << endl;
return 0;
}
cout << fixed << setprecision(2) << result << endl; //设置输出精度为两位小数
return 0;
}
```
运行示例:
```
Please input two integers and an operator (+, -, *, /): 3 4 +
7.00
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)