分别定义四个函数,求两个整数的和、差、积、商。在main()函数中输入两个整数和运算符,根据用户输入的运算符调用对应的函数,并将结果输出,要求结果保留两位小数。
时间: 2024-02-20 16:57:53 浏览: 52
好的,以下是你需要的代码:
#include <iostream>
#include <iomanip>
using namespace std;
// 定义函数,求两数之和
float add(float a, float b) {
return a + b;
}
// 定义函数,求两数之差
float subtract(float a, float b) {
return a - b;
}
// 定义函数,求两数之积
float multiply(float a, float b) {
return a * b;
}
// 定义函数,求两数之商
float divide(float a, float b) {
return a / b;
}
int main() {
float a, b, result;
char op;
cout << "请输入两个整数和运算符,以空格分隔:" << endl;
cin >> a >> b >> op;
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 << "无效的运算符!" << endl;
return 1;
}
cout << fixed << setprecision(2); // 设置输出格式,保留两位小数
cout << a << " " << op << " " << b << " = " << result << endl;
return 0;
}
首先定义了四个函数,分别用于求两数之和、差、积、商。在主函数中,先输入两个整数和运算符,根据运算符调用对应的函数,求出结果,并使用fixed
和setprecision
函数设置输出格式,保留两位小数。最后将结果输出。
相关推荐


















