// rational.cpp // member function definitions for rational.cpp #include using std::cout; #include "rational.h" // constructor Rational::Rational( int n, int d ) { numerator = n; denominator = d; } // end class Rational constructor // add rational numbers Rational Rational::addition( const Rational &a ) { Rational t; t.numerator = a.numerator * denominator; t.numerator += a.denominator * numerator; t.denominator = a.denominator * denominator; t.reduction(); return t; } // end function addition // subtract rational numbers Rational Rational::subtraction( const Rational &s ) { Rational t; t.numerator = s.denominator * numerator; t.numerator -= denominator * s.numerator; t.denominator = s.denominator * denominator; t.reduction(); return t; } // end function subtraction // multiply rational numbers Rational Rational::multiplication( const Rational &m ) { Rational t; t.numerator = m.numerator * numerator; t.denominator = m.denominator * denominator; t.reduction(); return t; } // end function multiplication // divide rational numbers Rational Rational::division( const Rational &v ) { Rational t; t.numerator = v.denominator * numerator; t.denominator = denominator * v.numerator; t.reduction(); return t; } // end function division // print rational numbers void Rational::printRational() { if ( denominator == 0 ) cout << "\nDIVIDE BY ZERO ERROR!!!\n"; else if ( numerator == 0 ) cout << 0; else cout << numerator << '/' << denominator; } // end function printRational // print rational numbers as doubles void Rational::printRationalAsDouble() { cout << static_cast< double >( numerator ) / denominator; } // end function printRationalAsDouble // helper function reduction definition void Rational::reduction() { int smallest; smallest = numerator < denominator ? numerator : denominator; int gcd = 0; // greatest common divisor for ( int loop = 2; loop <= smallest; ++loop ) if ( numerator % loop == 0 && denominator % loop == 0 ) gcd = loop; if ( gcd != 0 ) { numerator /= gcd; denominator /= gcd; } // end if } // end helper function reduction /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and Prentice * * Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/