1. 生成一个Rational(有理数类),执行带分数的运算(整数部分和分数部分分别表示),编写测试代码。用整数表示类的private数据(分子,分母),提供一个构造函数,初始化对象,不提供初始化值,则使用默认值并将分数以最简分数的形式存放,如2/4存放分子1,分母2。实现两个有理数的减法,乘法,结果以最简分数形式保存。
时间: 2023-06-14 17:03:09 浏览: 239
下面是Rational类的实现代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
Rational(int num = 0, int den = 1) {
if (den == 0) {
cout << "Error: denominator cannot be zero" << endl;
exit(1);
}
int gcd = __gcd(num, den);
numerator = num / gcd;
denominator = den / gcd;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
void print() const {
if (denominator == 1) {
cout << numerator;
} else {
cout << numerator << "/" << denominator;
}
}
Rational operator+(const Rational &other) const {
int num = numerator * other.denominator + other.numerator * denominator;
int den = denominator * other.denominator;
return Rational(num, den);
}
Rational operator-(const Rational &other) const {
int num = numerator * other.denominator - other.numerator * denominator;
int den = denominator * other.denominator;
return Rational(num, den);
}
Rational operator*(const Rational &other) const {
int num = numerator * other.numerator;
int den = denominator * other.denominator;
return Rational(num, den);
}
};
int main() {
Rational r1(2, 4);
Rational r2(3, 5);
Rational r3 = r1 - r2;
Rational r4 = r1 * r2;
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;
return 0;
}
```
输出结果如下:
```
r1 = 1/2
r2 = 3/5
r1 - r2 = -1/10
r1 * r2 = 3/10
```
在Rational类的构造函数中,我们首先判断分母是否为0,如果是则报错退出程序。然后使用STL中的__gcd()函数求出分子和分母的最大公约数,将其约分为最简分数形式。如果分母为负数,则将分子和分母都变为相反数。
在Rational类中,我们重载了加、减、乘三种运算符,用于对两个有理数的加、减、乘运算。在每个运算符中,我们使用通分的方法将两个有理数的分母相乘,然后对分子进行相应的运算,最后将结果存放到一个新的Rational对象中,返回该对象。在返回结果之前,我们还需要将其约分为最简分数形式。
阅读全文