home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_10_07 / 1007060a < prev    next >
Text File  |  1992-05-06  |  1KB  |  95 lines

  1. #include "mylib.h"
  2. #include "rational.h"
  3.  
  4. rational rational::operator-()
  5.     {
  6.     rational result(*this);
  7.     result.num = -result.num;
  8.     return result;
  9.     }
  10.  
  11. rational operator++(rational &r, int)
  12.     {
  13.     rational result(r);
  14.     r += 1;
  15.     return result;
  16.     }
  17.  
  18. rational operator--(rational &r, int)
  19.     {
  20.     rational result(r);
  21.     r -= 1;
  22.     return result;
  23.     }
  24.  
  25. rational &rational::operator+=(rational r)
  26.     {
  27.     num = num * r.denom + r.num * denom;
  28.     denom *= r.denom;
  29.     simplify();
  30.     return *this;
  31.     }
  32.  
  33. rational &rational::operator-=(rational r)
  34.     {
  35.     num = num * r.denom - r.num * denom;
  36.     denom *= r.denom;
  37.     simplify();
  38.     return *this;
  39.     }
  40.  
  41. rational &rational::operator*=(rational r)
  42.     {
  43.     num *= r.num;
  44.     denom *= r.denom;
  45.     simplify();
  46.     return *this;
  47.     }
  48.  
  49. rational &rational::operator/=(rational r)
  50.     {
  51.     num *= r.denom;
  52.     denom *= r.num;
  53.     simplify();
  54.     return *this;
  55.     }
  56.  
  57. ostream &operator<<(ostream &os, rational r)
  58.     {
  59.     return os << '(' << r.num << '/' << r.denom << ')';
  60.     }
  61.  
  62. istream &operator>>(istream &is, rational &r)
  63.     {
  64.     long n, d;
  65.     char c = 0;
  66.     if (is >> c && c == '(')
  67.         {
  68.         is >> n >> c;
  69.         if (c == '/')
  70.             is >> d >> c;
  71.         if (c != ')')
  72.             {
  73.             is.putback(c);
  74.             is.clear(ios::failbit);
  75.             }
  76.         }
  77.     else
  78.         {
  79.         is.putback(c);
  80.         is >> n;
  81.         d = 1;
  82.         }
  83.     if (is)
  84.         r = rational(n, d);
  85.     return is;
  86.     }
  87.  
  88. void rational::simplify()
  89.     {
  90.     long x = gcd(num, denom);
  91.     num /= x;
  92.     denom /= x;
  93.     }
  94.  
  95.