C++ 分数化简函数问题

来源:百度知道 编辑:UC知道 时间:2024/06/23 05:06:08
Rational Rational:: easy()
{
Rational d(*this),e(*this);
int c=1;
while(c)
{
c=d.numerator%d.demoniator;
d.numerator=d.demoniator;
d.demoniator=c;
}
e.numerator/=d.numerator;
e.demoniator/=d.numerator;
return e;
}

对于以上函数,
Rational e(2,4);
e(e.easy());
得到的e为什么还是(2,4)而不是(1,2)
但是如果
Rational e(2,4);
Rational d(e.easy());
这时候d就被化简成(1,2)了,why?

Rational e(2,4);
e(e.easy());
这样没错?e已经被创建了
Rational e(2,4);
Rational d(e.easy());
d是新的对象,调用复制构造函数

你没有修改当前对象,你修改的是临时对象e。

#include <iostream>

using namespace std;

class Rational {
public:
Rational(int n, int d) :numerator(n), denominator(d) {}
Rational& reduce();

int numerator;
int denominator;
};

int gcd(int x, int y) {
int z;
while ((z = x % y) != 0) {
x = y;
y = z;
}
return y;
}

Rational& Rational::reduce() {
int g = gcd(numerator, denominator);
numerator /= g;
denominator /= g;
return *this;
}

int main()
{
Rational r(12, 9);
r.reduce();
cout << r.numerator << ' ' << r.denominator << endl;
return 0;
}