#include<iostream>
using namespace std;
class Fraction {
private:
int m_numerator = 0;
int m_denominator = 1;
public:
int getdenominator() const { return m_denominator; } //获取分母
int getnumerator() const { return m_numerator; } //获取分子
void setdenominator(int a) { m_denominator = a; }
void setnumerator(int b) { m_numerator = b; }
void reduction(Fraction d1, Fraction d2);
int gcd(int x, int y);
void reduce();
Fraction(int above = 0, int below = 1) :
m_numerator(above), m_denominator(below) {
cout << "Constructor called" << endl;
}
Fraction(const Fraction& rhs) : m_numerator(rhs.m_numerator), \
m_denominator(rhs.m_denominator) {
cout << "Copy constructor called" << endl;
}
~Fraction() {} //析构函数
};
Fraction divide1(const Fraction& divident, const Fraction& divisor) {
return Fraction(divident.getnumerator() * divisor.getdenominator(), \
divident.getdenominator() * divisor.getnumerator());
}
Fraction divide2(Fraction divident, Fraction divisor) {
Fraction result(divident.getnumerator() * divisor.getdenominator(), \
divident.getdenominator() * divisor.getnumerator());
return result;
}
int Fraction::gcd(int x, int y) //求最大公因数
{
if (y != 0)
return gcd(y, x % y);
else return x;
}
void Fraction::reduce() //约分
{
int n = gcd(m_denominator, m_numerator);
m_denominator = m_denominator / n;
m_numerator = m_numerator / n;
}
void Fraction::reduction(Fraction d1, Fraction d2) //通分
{
for (int k = 1; k <= (d1.getdenominator() * d2.getdenominator()); k++)
{
if (k % d1.getdenominator() == 0 && k % d2.getdenominator() == 0)
{
d1.m_numerator = d1.m_numerator * (k / d1.m_denominator);
d2.m_numerator = d2.m_numerator * (k / d2.m_denominator);
d1.setdenominator(k);
d2.setdenominator(k);
break;
}
}
}
Fraction operator/(const Fraction& right, const Fraction& left) //使用 operator/操作符重载实现两个分数的除法运算。
{
Fraction result(left.getnumerator() * right.getdenominator(), left.getdenominator() * right.getdenominator());
return result;
}
1218上机
最新推荐文章于 2024-08-18 21:07:18 发布