pta 基本fraction分数类
时间: 2023-07-29 10:05:44 浏览: 139
下面是一个基本的 C++ 类实现,用于表示分数:
```cpp
#include <iostream>
using namespace std;
class Fraction {
private:
int numerator; // 分子
int denominator; // 分母
public:
Fraction(int n, int d) {
numerator = n;
denominator = d;
}
Fraction operator+(Fraction const &obj) {
int n = numerator * obj.denominator + obj.numerator * denominator;
int d = denominator * obj.denominator;
return Fraction(n, d);
}
Fraction operator-(Fraction const &obj) {
int n = numerator * obj.denominator - obj.numerator * denominator;
int d = denominator * obj.denominator;
return Fraction(n, d);
}
Fraction operator*(Fraction const &obj) {
int n = numerator * obj.numerator;
int d = denominator * obj.denominator;
return Fraction(n, d);
}
Fraction operator/(Fraction const &obj) {
int n = numerator * obj.denominator;
int d = denominator * obj.numerator;
return Fraction(n, d);
}
void simplify() {
int gcd = __gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
void display() {
if (denominator == 1) {
cout << numerator << endl;
} else {
cout << numerator << "/" << denominator << endl;
}
}
};
int main() {
Fraction f1(2, 3);
Fraction f2(3, 4);
Fraction f3 = f1 + f2;
f3.simplify();
f3.display();
Fraction f4 = f1 - f2;
f4.simplify();
f4.display();
Fraction f5 = f1 * f2;
f5.simplify();
f5.display();
Fraction f6 = f1 / f2;
f6.simplify();
f6.display();
return 0;
}
```
这个类实现了加、减、乘、除四个运算符重载,并且包含了化简分数以及显示分数的方法。在主函数中,我们创建了两个分数对象 `f1` 和 `f2`,然后通过运算符重载来对它们进行加减乘除的操作,并且将结果化简后输出。
阅读全文