home *** CD-ROM | disk | FTP | other *** search
- // \EXAMPLES\EX0804.H
- // definition of the Fraction classs
- //---------------------------------------------------------------
- // files in this example:
- // EX0804.H this file
- // %F,15,EX0804.CPP%EX0804.CPP main()
- //-------------------------------------------------------------
- #include <iostream.h>
- //-------------------------------------------------------------
- // Fraction class cut down to include only what is required
- // for this example
- //-------------------------------------------------------------
- class Fraction
- { private:
- int num; // numerator signed
- int denom; // demoninator always positive
- void reduce (); // reduces Fraction to simplest form
- int gcd( int n, int d); // greatest common divisor
- public: // default value num(0), denom(1)
- Fraction::Fraction( int i, int j );
- friend void print( const Fraction& F);
- inline Fraction operator-() const
- { return Fraction(-num,denom); }
- int operator<( const Fraction& f)
- { return num * f.denom < f.num * denom; }
- };
-
- Fraction::Fraction( int i=0, int j=1 ) : num(i), denom(j)
- { if (denom != 1) reduce();
- }
-
- //---------------------------------------------------------
- // private member function reduce --> to simlest form
- //---------------------------------------------------------
- void Fraction::reduce()
- { if ( denom == 0 ) // if demoninator 0
- { num = 0; denom = 1; } // set to 0/1
- if ( denom < 0 ) // if demoninator
- { num = - num; denom = - denom; } // move sing to num
- int g = gcd(num, denom); // find greatest common
- if (g > 1) // denominator
- { num = num/g; denom = denom/g;} // simplify fraction
- }
- //---------------------------------------------------------
- // Euclids algorithm for greatest common demoninator
- //---------------------------------------------------------
- int Fraction::gcd(int n, int d)
- { n = n < 0 ? -n : n; // use absolute value
- return n % d == 0 ? d : gcd( d, n % d); // recursive call gcd
- }
- //---------------------------------------------------------
-