Hi all!
I've written a class and test program which seems to cancel down fractions to their lowest equivalent form!
Firstly, I'd like to know if anybody can spot any flaws with the method.
Secondly, If you know a more efficent/elegant way of doing it, then please inform me!
Please find my code below!
Code:// Rational.h // Member functions defined in Rational.cpp #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int = 1, int = 2 ); // default constructor // Set functions void setNumerator( int ); void setDenominator( int ); // Get functions int getNumerator(); int getDenominator(); // Utility functions void simplify(); void print(); private: int numerator; int denominator; }; // end Rational class #endif // RATIONAL_HCode:// main.cpp #include <iostream> #include "Rational.h" using namespace std; int main() { Rational fraction1( 75, 100 ); fraction1.print(); } // end mainCode:// Rational.cpp #include "Rational.h" #include <iostream> using namespace std; // *** Constructor definition *** Rational::Rational( int Num, int Denom ) { setNumerator( Num ); setDenominator( Denom ); if ( getNumerator() != 1 ) { simplify(); } // end if } // end Rational constructor // *** Set function definition *** void Rational::setNumerator( int Num ) { if ( Num < 1 ) { Num = 0; } // end if numerator = Num; } // end function setNumerator void Rational::setDenominator( int Denom ) { while ( Denom < ( getNumerator() ) ) { cout << "NOT A VALID DENOMINATOR !!!"; } // end if denominator = Denom; } // end function setDenominator // *** Get function definition *** int Rational::getNumerator() { return numerator; } // end function getNumerator int Rational::getDenominator() { return denominator; } // end function getDenominator // *** Utility function definition *** void Rational::print() { cout << "(" << getNumerator() << ", " << getDenominator() << ")" << endl; } // end function print void Rational::simplify() { int counter = 2; int a = getNumerator(); int b = getDenominator(); bool bothDivisible = true; while ( bothDivisible == true ) { for ( counter; counter <= a; counter++ ) { if ( a % counter == 0 && b % counter == 0 ) { setNumerator( a / counter ); setDenominator( b / counter ); simplify(); } // end if } // end for bothDivisible = false; } // end while } // end function simplify



1Likes
LinkBack URL
About LinkBacks


