设计有理数类,利用运算符重载实现有理数+,-,*,/运算和输出。利用该有理数类,实现两个有理数的运算和结果输出。有理数需化简,有理数分母为1时分母不输出,分母始终大于 0。 输入格式: 一对分子分母代表一个有理数,分别输入两个有理数 输出格式: 两个有理数(2行)和它们的和、差、积、商(1 行,利用tab键'\t'分隔)
时间: 2024-03-07 20:50:21 浏览: 134
好的,我知道了。以下是有理数类的实现代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
// 构造函数
Rational(int num = 0, int den = 1) {
if (den == 0) {
cout << "分母不能为0!" << endl;
exit(-1);
}
if (den < 0) {
num = -num;
den = -den;
}
int gcd_num_den = gcd(abs(num), den);
numerator = num / gcd_num_den;
denominator = den / gcd_num_den;
}
// 加法运算符重载
Rational operator+(const Rational& r) {
int num = numerator * r.denominator + r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
// 减法运算符重载
Rational operator-(const Rational& r) {
int num = numerator * r.denominator - r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
// 乘法运算符重载
Rational operator*(const Rational& r) {
int num = numerator * r.numerator;
int den = denominator * r.denominator;
return Rational(num, den);
}
// 除法运算符重载
Rational operator/(const Rational& r) {
int num = numerator * r.denominator;
int den = denominator * r.numerator;
return Rational(num, den);
}
// 输出运算符重载
friend ostream& operator<<(ostream& os, const Rational& r) {
if (r.denominator == 1) {
os << r.numerator;
} else {
os << r.numerator << "/" << r.denominator;
}
return os;
}
// 获取分子
int getNumerator() const {
return numerator;
}
// 获取分母
int getDenominator() const {
return denominator;
}
private:
// 辗转相除法求最大公约数
int gcd(int m, int n) {
int r;
while (n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}
};
int main() {
int num1, den1, num2, den2;
cin >> num1 >> den1 >> num2 >> den2;
Rational r1(num1, den1);
Rational r2(num2, den2);
cout << r1 << endl;
cout << r2 << endl;
cout << r1 + r2 << "\t" << r1 - r2 << "\t" << r1 * r2 << "\t" << r1 / r2 << endl;
return 0;
}
```
输入格式为:两对分子和分母,分别代表两个有理数。
输出格式为:先输出两个有理数,然后输出它们的和、差、积、商,用制表符 `\t` 分隔开。
阅读全文