1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
int main ()
{
#include <iostream>
using namespace std;
class Rational
{
public :
Rational(int initNumerator, unsigned int initDenominator );
Rational(int initNumerator);
int getNumerator() ;
unsigned int getDenominator() ;
Rational add(const Rational& addend) ;
Rational sub(const Rational& subtractor);
Rational mul(const Rational& factor) ;
Rational div(const Rational& divisor) ;
bool less(const Rational& rhs) ;
Rational neg() ;
void output (ostream& outputStream);
void input (istream& inputStream);
private :
int numerator;
unsigned int denominator;
char c;
};
int main ()
{
Rational a (1,4);
Rational b (3,4);
a.add(b).output(cout);//correct output given
a.sub(b).output(cout);//correct output given
a.mul(b).output(cout);//correct output given
a.div(b).output(cout);//correct output given
a.less(b).output(cout);
|
}
Rational::Rational (int initNumerator, unsigned int initDenominator)//class definitions{
{
numerator = initNumerator;
denominator = initDenominator;
}
void Rational::output (ostream & anOstream)
{
anOstream << numerator << '/' << denominator;
}
void Rational:: input (istream& inputStream)
{
inputStream >> numerator >> c >> denominator;
}
int Rational::getNumerator ()
{return this -> numerator;}
unsigned int Rational::getDenominator ()
{return this -> denominator;}
Rational Rational::add (const Rational& addend)
{
Rational result
((this -> numerator * addend.denominator + this -> denominator * addend.numerator),
(this -> denominator * addend.denominator));
return result;
}
Rational Rational::sub (const Rational& subtractor)
{
Rational result
((this -> numerator * subtractor.denominator - this -> denominator * subtractor.numerator),
(this -> denominator * subtractor.denominator));
return result;
}
Rational Rational::mul (const Rational& factor)
{
Rational result
((this -> numerator * factor.numerator),
(this -> denominator * factor.denominator));
return result;
}
Rational Rational::div ( const Rational& divisor )
{
Rational result
((this->numerator * divisor.denominator),
(this->denominator * divisor.numerator )) ;
return result ;
} // end operator/ function
bool Rational::less(const Rational& rhs)
{
int leftHandSide = this->numerator * rhs.denominator;
int rightHandSide = rhs.numerator * this->denominator;
return leftHandSide < rightHandSide;
}
Rational Rational::neg()
{
return Rational( -(this->numerator), this->denominator);
}
} |