home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_09 / allison / rational.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-10  |  625 b   |  41 lines

  1. #include <iostream.h>
  2. #include "rational.h"
  3.  
  4. // Link to existing C function:
  5. extern "C" int gcd(int, int);
  6.  
  7. // Reduce fraction lowest terms
  8. void Rational::reduce()
  9. {
  10.     int g = gcd(num,den);
  11.  
  12.     if (g > 1)
  13.     {
  14.         num /= g;
  15.         den /= g;
  16.     }
  17. }
  18.  
  19. istream& operator>>(istream& is, Rational& r)
  20. {
  21.     char c;
  22.  
  23.     is >> r.num >> c;
  24.     if (c == '/')
  25.         is >> r.den;
  26.     else
  27.     {
  28.         r.den = 1;
  29.         is.putback(c);
  30.     }
  31.     r.reduce();
  32.     return is;
  33. }
  34.  
  35. ostream& operator<<(ostream& os, const Rational& r)
  36. {
  37.     os << r.num << " / " << r.den;
  38.     return os;
  39. }
  40.  
  41.