#include #include "rational.h" using namespace std; // implementation of the rational class rational::rational(int numer, int denom) { if (denom == 0) { throw invalid_argument("denominator = 0"); } numerator = numer; denominator = denom; fix_signs(); reduce(); } int rational::get_numerator() const{ return numerator; } int rational::get_denominator() const { return denominator; } // n1/d1 - n2/d2 = (n1 * d2 - n2 * d1) / (d1 * d2) rational & rational::operator-=(const rational & rhs) { numerator = numerator * rhs.denominator - rhs.numerator * denominator; denominator *= rhs.denominator; reduce(); return *this; } void rational::fix_signs() { if (denominator < 0) { numerator = -numerator; denominator = -denominator; } } // returns the greatest common divisor of x and y int gcd(int x, int y) { if (x < 0 || y < 0) { return gcd(abs(x), abs(y)); } else if (y == 0) { return x; } else { return gcd(y, x % y); } } void rational::reduce() { int common = gcd(numerator, denominator); numerator /= common; denominator /= common; } ostream & operator<<(ostream & out, const rational & value) { out << value.get_numerator(); if (value.get_denominator() != 1) { out << "/" << value.get_denominator(); } return out; } rational operator-(const rational & lhs, const rational & rhs) { rational result(lhs); result -= rhs; return result; } bool operator==(const rational & lhs, const rational & rhs) { return (lhs - rhs).get_numerator() == 0; } bool operator!=(const rational & lhs, const rational & rhs) { return !(lhs == rhs); } bool operator<(const rational & lhs, const rational & rhs) { return (lhs - rhs).get_numerator() < 0; } bool operator>(const rational & lhs, const rational & rhs) { return (lhs - rhs).get_numerator() > 0; } bool operator<=(const rational & lhs, const rational & rhs) { return (lhs - rhs).get_numerator() <= 0; } bool operator>=(const rational & lhs, const rational & rhs) { return (lhs - rhs).get_numerator() >= 0; } rational & rational::operator++() { numerator += denominator; return *this; } rational rational::operator++(int dummy) { rational result(*this); numerator += denominator; return result; }