// Class for rational numbers. #include #include using namespace std; class Rational { friend ostream &operator<<(ostream&, const Rational&); public: Rational(const int = 0, const int = 1); // Rational default constructor. Rational operator-() const; // Rational unary minus. Rational operator+(const Rational &) const; // Rational addition. Rational operator-(const Rational &) const; // Rational substraction. Rational operator*(const Rational &) const; // Rational multiplication. Rational operator/(const Rational &) const; // Rational division. private: int nume; // numerator (¤À¤l) int deno; // denominator (¤À¥À) void setRational(const int, const int); // Set new values to a rational object. int gcd(int, int); // GCD: greatest common divisor. Rational &simplify(); // Simplify a rational number. }; // Rational default constructor: a is the numerator and b is the denominator. Rational::Rational(const int a, const int b) { setRational(a, b); } // Rational unary minus. Rational Rational::operator-() const { Rational nega; nega.nume = -1 * nume; nega.deno = deno; return nega.simplify(); } // Rational addition. Rational Rational::operator+(const Rational &r) const { Rational sum; sum.nume = nume * r.deno + r.nume * deno; sum.deno = deno * r.deno; return sum.simplify(); } // Rational substraction. Rational Rational::operator-(const Rational &r) const { Rational diff; diff.nume = nume * r.deno - r.nume * deno; diff.deno = deno * r.deno; return diff.simplify(); } // Rational multiplication. Rational Rational::operator*(const Rational &r) const { Rational prod; prod.nume = nume * r.nume ; prod.deno = deno * r.deno; return prod.simplify(); } // Rational division. Rational Rational::operator/(const Rational &r) const { Rational quot; if (r.nume!=0) { quot.nume = nume * r.deno ; quot.deno = deno * r.nume; } else { quot.nume = 0; quot.deno = 1; } return quot.simplify(); } // Set new values to a rational object. void Rational::setRational(const int p , const int q) { nume = p; deno = q; this->simplify(); } // GCD: greatest common divisor. int Rational::gcd(int m, int n) { m = abs(m); n = abs(n); if (m % n == 0) return n; else return gcd(n, m % n); } // Simplify rational number r. Rational &Rational::simplify() { int g; if (deno==0) {nume = 0; deno = 1;} else if (deno<0) {nume = -nume; deno = -deno;} g = gcd(nume, deno); nume = nume / g; deno = deno / g; return *this; } ostream &operator<<(ostream& output, const Rational& r) { if (r.nume==0) output << "0"; else if (r.deno==1) output << r.nume; else output << r.nume << "/" << r.deno; return output; } int main(void) { Rational a(3, 5), b(-2, 3), c(3, 1), d(-2, 1), e(10, 3); cout << "a = " << a << ", b = " << b << ", c = " << c << ", d = " << d << ", e = " << e << endl << endl; cout << "a + (b - c * d) / e = " << a + (b - c * d) / e << endl; cout << "a + (b - c * d) / e = " << a.operator+(b.operator-(c.operator*(d)).operator/(e)) << endl << endl; system("pause"); }