home *** CD-ROM | disk | FTP | other *** search
- // \EXAMPLES\EX0801.H
- // definition of the Fraction class
- //---------------------------------------------------------------
- // files in this example:
- // EX0801.H this file
- // %F,15,EX0801.CPP%EX0801.CPP main program
- //---------------------------------------------------------
- #include <iostream.h>
- //--------------------------------------------------------
- // Defintion of the Fraction class
- //--------------------------------------------------------
- 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 constructor, convertion from integer
- //------------------------------------------------------
- Fraction( int i=0, int j=1) : num(i), denom(j)
- { reduce(); }
- //------------------------------------------------------
- // three wasy to output a fraction
- //-------------------------------------------------------
- void display()
- { cout << num << "/" << denom; };
-
- friend void print( const Fraction& F);
-
- friend
- ostream& operator<<(ostream& os, const Fraction& f);
- //-------------------------------------------------------
- // one function to input a fraction
- //-------------------------------------------------------
- friend void read(Fraction& F);
- };
- //---------------------------------------------------------
- // 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
- }
- //---------------------------------------------------------
-