建立一个分数类。分数类的数据成员包括分子和分母,成员函数包括显示、输入、约分、通分、比较、加、减、乘、除、求相反数。
时间: 2024-06-17 13:05:47 浏览: 190
好的,建立一个分数类的代码如下:
```
#include <iostream>
#include <algorithm>
using namespace std;
class Fraction {
public:
Fraction(int num = 0, int den = 1) : numerator(num), denominator(den) {}
void display() const {
cout << numerator << "/" << denominator << endl;
}
void input() {
cin >> numerator >> denominator;
}
void reduce() {
int gcd = __gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
void to_common(Fraction &f) {
int lcm = denominator / __gcd(denominator, f.denominator) * f.denominator;
numerator *= lcm / denominator;
denominator = lcm;
f.numerator *= lcm / f.denominator;
f.denominator = lcm;
}
bool operator < (const Fraction &f) const {
return numerator * f.denominator < denominator * f.numerator;
}
bool operator > (const Fraction &f) const {
return numerator * f.denominator > denominator * f.numerator;
}
bool operator == (const Fraction &f) const {
return numerator * f.denominator == denominator * f.numerator;
}
Fraction operator + (const Fraction &f) const {
Fraction res(numerator * f.denominator + f.numerator * denominator, denominator * f.denominator);
res.reduce();
return res;
}
Fraction operator - (const Fraction &f) const {
Fraction res(numerator * f.denominator - f.numerator * denominator, denominator * f.denominator);
res.reduce();
return res;
}
Fraction operator * (const Fraction &f) const {
Fraction res(numerator * f.numerator, denominator * f.denominator);
res.reduce();
return res;
}
Fraction operator / (const Fraction &f) const {
Fraction res(numerator * f.denominator, denominator * f.numerator);
res.reduce();
return res;
}
Fraction operator - () const {
return Fraction(-numerator, denominator);
}
private:
int numerator;
int denominator;
};
int main() {
Fraction a(2, 3), b(4, 6);
a.display(); // 2/3
b.display(); // 4/6
b.reduce();
b.display(); // 2/3
a.to_common(b);
a.display(); // 4/6
b.display(); // 4/6
if (a < b) cout << "a < b" << endl; // a < b
if (a > b) cout << "a > b" << endl;
if (a == b) cout << "a == b" << endl; // a == b
(a + b).display(); // 8/6
(a - b).display(); // 0/6
(a * b).display(); // 8/18
(a / b).display(); // 8/12
(-a).display(); // -4/6
}
```
这个代码实现了分数类,包括了显示、输入、约分、通分、比较、加、减、乘、除、求相反数等成员函数。
阅读全文