用c++编写分数的运算符重载完整的程序 包括主函数
时间: 2023-06-09 13:02:49 浏览: 120
好的,请稍等一下,让我思考一下。
以下是用c++编写分数的运算符重载的完整程序,包括主函数。您可以参考一下:
```
#include <iostream>
using namespace std;
class Fraction {
private:
int numerator; // 分子
int denominator; // 分母
public:
Fraction(int num = 0, int den = 1) {
numerator = num;
denominator = den;
while (denominator == 0) {
cout << "分母不能为0,请重新输入!" << endl;
cout << "分子:" << endl;
cin >> numerator;
cout << "分母:" << endl;
cin >> denominator;
}
reduce();
}
void reduce() { // 约分
int sign = 1;
if (numerator < 0)
sign = -sign;
if (denominator < 0)
sign = -sign;
int n = abs(numerator), d = abs(denominator);
int gcd = 1;
for (int i = 1; i <= n && i <= d; i++)
if (n % i == 0 && d % i == 0)
gcd = i;
numerator = sign * (numerator / gcd);
denominator = abs(denominator / gcd);
}
Fraction operator +(const Fraction& f) const { // 加法重载
Fraction res;
res.denominator = denominator * f.denominator;
res.numerator = numerator * f.denominator + f.numerator * denominator;
res.reduce();
return res;
}
Fraction operator -(const Fraction& f) const { // 减法重载
Fraction res;
res.denominator = denominator * f.denominator;
res.numerator = numerator * f.denominator - f.numerator * denominator;
res.reduce();
return res;
}
Fraction operator *(const Fraction& f) const { // 乘法重载
Fraction res;
res.numerator = numerator * f.numerator;
res.denominator = denominator * f.denominator;
res.reduce();
return res;
}
Fraction operator /(const Fraction& f) const { // 除法重载
Fraction res;
res.numerator = numerator * f.denominator;
res.denominator = denominator * f.numerator;
res.reduce();
return res;
}
friend ostream& operator <<(ostream& os, const Fraction& f) { // 输出重载
os << f.numerator << "/" << f.denominator;
return os;
}
};
int main() {
int num1, den1, num2, den2;
cout << "请输入第一个分数的分子:" << endl;
cin >> num1;
cout << "请输入第一个分数的分母:" << endl;
cin >> den1;
cout << "请输入第二个分数的分子:" << endl;
cin >> num2;
cout << "请输入第二个分数的分母:" << endl;
cin >> den2;
Fraction f1(num1, den1);
Fraction f2(num2, den2);
cout << "加法结果为:" << f1 + f2 << endl;
cout << "减法结果为:" << f1 - f2 << endl;
cout << "乘法结果为:" << f1 * f2 << endl;
cout << "除法结果为:" << f1 / f2 << endl;
return 0;
}
```
希望这个程序对您有所帮助!
阅读全文