#include #include #include #include "rational.h" using namespace std; int gcd(int x, int y) { int a = y; while (a != 0) { y = a; a = x % a; x = y; } return x; } rational::rational() { top=0; bottom=1; } rational::rational(int i) { top=i; bottom=1; } rational::rational(int i, int j) { assert(j!=0); top=i; bottom=j; normalize(); } rational::rational(const rational &source) { top=source.top; bottom=source.bottom; } int rational::numerator() const{ return top; } int rational::denominator() const{ return bottom; } void rational::operator = (const rational &r) { top = r.top; bottom = r.bottom; } void rational::operator += (const rational &r) { top = top * r.bottom + r.top * bottom; bottom = r.bottom * bottom; (*this).normalize(); } void rational::operator -= (const rational &r) { top = top * r.bottom - r.top * bottom; bottom = r.bottom * bottom; (*this).normalize(); } void rational::operator *= (const rational &r) { top = top * r.top; bottom = bottom * r.bottom; (*this).normalize(); } void rational::operator /= (const rational &r) { top = top * r.bottom; bottom = bottom * r.top; (*this).normalize(); } // returns 1 if p > q, returns 0 if p = q, and -1 if p < q int rational::compare(const rational &r) const { if (top * r.bottom > bottom * r.top) return 1; if (top * r.bottom < bottom * r.top) return -1; return 0; } void rational::normalize() { int m = gcd(top, bottom); assert(m != 0); top /= m; bottom /= m; }