分别定义四个函数,求两个整数的和,差,积商。在main()函数中输入两个整数和运算符,根据用户输入的运算符调用对应的函数,并将结果输出,要求结果保留两位小数
时间: 2024-02-03 15:12:42 浏览: 23
以下是代码示例:
```c++
#include <iostream>
#include <iomanip> // 用于设置输出精度
using namespace std;
// 求两个整数的和
double add(int a, int b) {
return a + b;
}
// 求两个整数的差
double subtract(int a, int b) {
return a - b;
}
// 求两个整数的积
double multiply(int a, int b) {
return a * b;
}
// 求两个整数的商
double divide(int a, int b) {
if (b == 0) {
cout << "除数不能为0!" << endl;
return 0;
}
return (double) a / b;
}
int main() {
int a, b;
char op;
cin >> a >> op >> b;
double res; // 存储结果
switch (op) {
case '+':
res = add(a, b);
break;
case '-':
res = subtract(a, b);
break;
case '*':
res = multiply(a, b);
break;
case '/':
res = divide(a, b);
break;
default:
cout << "输入错误!" << endl;
return 0;
}
cout << fixed << setprecision(2) << res << endl; // 设置输出精度为2位小数
return 0;
}
```
输入格式为:`a 运算符 b`,其中运算符包括加号`+`、减号`-`、乘号`*`和除号`/`。运行结果如下:
```
1 + 2
3.00
5 - 3
2.00
4 * 6
24.00
5 / 0
除数不能为0!
0.00
1 % 2
输入错误!
0.00
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)