定义一个有理数类。一个有理数类是一个可以表示成两个整数相除的数,如1/2、2/3、4/5。一个有理数类有两个整数成员表示:分子和分母。 (1)定义合适的构造函数完成有理数初始化。 (2)能以“1/2”这种样式输出有理数。 (3)重载运算符+,实现两个有理数的加法:a/b+c/d=(a*d+b*c)/(b*d) (4)重载运算符-,实现两个有理数的减法:a/b-c/d=(a*d-b*c)/(b*d) (5)重载运算符*,实现两个有理数的的乘法:(a/b)*(c/d)=(a*c)/(b*d) (6)重载运算符/,实现两个有理数的除法:(a/b)/(c/d)=(a*d)/(c*b) (7)重载运算符==,判断两个有理数是否相等 (8)重载运算符>,判断两个有理数的大小 (9)重载运算符<,判断两个有理数的大小
时间: 2024-02-21 17:02:06 浏览: 165
xt.rar_4 3 2 1
实现代码如下:
```c++
#include <iostream>
using namespace std;
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
Rational(int num = 0, int den = 1) {
numerator = num;
denominator = den;
}
void print() {
cout << numerator << "/" << denominator;
}
friend Rational operator+(Rational& r1, Rational& r2) {
int num = r1.numerator * r2.denominator + r2.numerator * r1.denominator; // 分子相加
int den = r1.denominator * r2.denominator; // 分母相乘
return Rational(num, den);
}
friend Rational operator-(Rational& r1, Rational& r2) {
int num = r1.numerator * r2.denominator - r2.numerator * r1.denominator; // 分子相减
int den = r1.denominator * r2.denominator; // 分母相乘
return Rational(num, den);
}
friend Rational operator*(Rational& r1, Rational& r2) {
int num = r1.numerator * r2.numerator; // 分子相乘
int den = r1.denominator * r2.denominator; // 分母相乘
return Rational(num, den);
}
friend Rational operator/(Rational& r1, Rational& r2) {
int num = r1.numerator * r2.denominator; // 分子相乘
int den = r1.denominator * r2.numerator; // 分母相乘
return Rational(num, den);
}
friend bool operator==(Rational& r1, Rational& r2) {
return r1.numerator * r2.denominator == r2.numerator * r1.denominator;
}
friend bool operator>(Rational& r1, Rational& r2) {
return r1.numerator * r2.denominator > r2.numerator * r1.denominator;
}
friend bool operator<(Rational& r1, Rational& r2) {
return r1.numerator * r2.denominator < r2.numerator * r1.denominator;
}
};
int main() {
Rational r1(1, 2);
Rational r2(2, 3);
Rational r3 = r1 + r2;
Rational r4 = r1 - r2;
Rational r5 = r1 * r2;
Rational r6 = r1 / r2;
Rational r7(1, 2);
Rational r8(2, 4);
cout << "r1 = ";
r1.print();
cout << endl;
cout << "r2 = ";
r2.print();
cout << endl;
cout << "r1 + r2 = ";
r3.print();
cout << endl;
cout << "r1 - r2 = ";
r4.print();
cout << endl;
cout << "r1 * r2 = ";
r5.print();
cout << endl;
cout << "r1 / r2 = ";
r6.print();
cout << endl;
if (r1 == r7) {
cout << "r1 equals r7" << endl;
} else {
cout << "r1 does not equal r7" << endl;
}
if (r1 == r8) {
cout << "r1 equals r8" << endl;
} else {
cout << "r1 does not equal r8" << endl;
}
if (r1 > r2) {
cout << "r1 is greater than r2" << endl;
} else {
cout << "r1 is not greater than r2" << endl;
}
if (r1 < r2) {
cout << "r1 is less than r2" << endl;
} else {
cout << "r1 is not less than r2" << endl;
}
return 0;
}
```
输出结果为:
```
r1 = 1/2
r2 = 2/3
r1 + r2 = 7/6
r1 - r2 = -1/6
r1 * r2 = 1/3
r1 / r2 = 3/4
r1 equals r7
r1 equals r8
r1 is not greater than r2
r1 is less than r2
```
阅读全文