// rational.cpp -- implementation of simple Rational number class. // cse143 assignment 1 sample solution, Jan. 1999. HP // Note: This implementation uses assert to trap some errors. This // was not required in the assignment. The relational operators // have also been changed to have a result type of bool. #include #include #include #include "rational.h" // ----- prototype and definition of private function ----- // = greatest common divisor of x and y. // Precondition: x != 0 && y != 0. static int gcd (int x, int y); static int gcd(int x, int y) { assert(x != 0 && y != 0); x = abs(x); y = abs(y); while (x != y) if (x > y) x = x-y; else // x > y y = y-x; return x; } // Note: The only place in the implementation where common factors // need to be divided out is in the Rational(int,int) constructor. // All other functions that yield Rational values use this constructor // to create the value after calculating the numerator and denominator. // ----- constructors ----- // = 0/1 Rational::Rational() { nm=0; dn=1; } // = n/1 Rational::Rational(int n) { nm = n; dn = 1; } // = n/d. Precondition: d != 0. Rational::Rational(int n, int d) { int div; // greatest common divisor of n and d assert(d != 0); nm = n; dn = d; // If numerator is 0, set denominator to 1. if (nm == 0) { dn = 1; } else { // numerator != 0. invert signs if needed to make denominator > 0. if (dn < 0) { nm = -nm; dn = -dn; } // divide out common factors of numerator and denominator div = gcd(nm,dn); nm = nm/div; dn = dn/div; } } // ----- component access ----- // = numerator of r int num(Rational r) { return r.nm; } // = denominator of r int denom(Rational r) { return r.dn; } // ----- arithmetic operations ----- // = r1 + r2 Rational operator+(Rational r1, Rational r2) { return Rational(r1.nm*r2.dn + r2.nm*r1.dn, r1.dn*r2.dn); } // = -r Rational operator-(Rational r) { return Rational(-r.nm, r.dn); } // = r1 - r2 Rational operator-(Rational r1, Rational r2) { return Rational(r1.nm*r2.dn - r2.nm*r1.dn, r1.dn*r2.dn); } // = r1 * r2 Rational operator*(Rational r1, Rational r2) { return Rational(r1.nm*r2.nm, r1.dn*r2.dn); } // = r1 / r2 Rational operator/(Rational r1, Rational r2) { return Rational(r1.nm*r2.dn, r1.dn*r2.nm); } // ----- relational operators ----- // = r1 < r2 bool operator<(Rational r1, Rational r2) { return (r1.nm*r2.dn < r2.nm*r1.dn); } // = r1 <= r2 bool operator<=(Rational r1, Rational r2) { return (r1.nm*r2.dn <= r2.nm*r1.dn); } // = r1 == r2 bool operator==(Rational r1, Rational r2) { return (r1.nm*r2.dn == r2.nm*r1.dn); } // = r1 != r2 bool operator!=(Rational r1, Rational r2) { return !(r1==r2); } // = r1 > r2 bool operator>(Rational r1, Rational r2) { return !(r1<=r2); } // = r1 >= r2 bool operator>=(Rational r1, Rational r2) { return !(r1