home *** CD-ROM | disk | FTP | other *** search
/ Microsoftware Monthly 19…2 Programming Power Tools / MASO9512.ISO / cpptutor / cpptutor.arj / EXAMPLES / EX0804.H < prev    next >
Encoding:
C/C++ Source or Header  |  1993-10-27  |  2.2 KB  |  52 lines

  1. // \EXAMPLES\EX0804.H
  2. //  definition of the Fraction classs
  3. //---------------------------------------------------------------
  4. // files in this example:
  5. // EX0804.H       this file
  6. // %F,15,EX0804.CPP%EX0804.CPP      main()
  7. //-------------------------------------------------------------
  8. #include <iostream.h>
  9. //-------------------------------------------------------------
  10. // Fraction class cut down to include only what is required
  11. //  for this example
  12. //-------------------------------------------------------------
  13.  class Fraction
  14. { private:
  15.    int   num;                // numerator signed
  16.    int   denom;              // demoninator always positive
  17.    void  reduce ();          // reduces Fraction to simplest form
  18.    int gcd( int n, int d);   // greatest common divisor
  19. public:                      // default value num(0), denom(1)
  20.    Fraction::Fraction( int i, int j );
  21.    friend void print( const Fraction& F);
  22.    inline Fraction operator-() const
  23.    { return Fraction(-num,denom); }
  24.    int operator<( const Fraction& f)
  25.    { return num * f.denom < f.num * denom; }
  26. };
  27.  
  28. Fraction::Fraction( int i=0, int j=1 ) : num(i), denom(j)
  29. {  if (denom != 1) reduce();
  30. }
  31.  
  32. //---------------------------------------------------------
  33. // private member function reduce --> to simlest form
  34. //---------------------------------------------------------
  35. void Fraction::reduce()
  36. { if ( denom == 0 )                     // if demoninator 0
  37.   {  num = 0; denom = 1; }                 //  set to 0/1
  38.   if ( denom < 0 )                      // if demoninator
  39.   { num = - num; denom = - denom; }        //  move sing to num
  40.   int g = gcd(num, denom);              // find greatest common
  41.   if (g > 1)                               //  denominator
  42.   { num = num/g; denom = denom/g;}      // simplify fraction
  43. }
  44. //---------------------------------------------------------
  45. // Euclids algorithm for greatest common demoninator
  46. //---------------------------------------------------------
  47. int Fraction::gcd(int n, int d)
  48. { n = n < 0 ? -n : n;                      // use absolute value
  49.   return n % d == 0 ? d : gcd( d, n % d);  // recursive call gcd
  50. }
  51. //---------------------------------------------------------
  52.