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 77 78 79 80 81 82
|
#include <iostream>
#include "Rational.h"
using namespace std;
Rational::Rational()
{
}
Rational::Rational(int a,int b)
{
setNumerator(a);
if(b>0)
setDenominator(b);
else
{
cout << "The denominator cannot be 0. It will be intialized as 1." << endl;
denominator=1;
}
}
Rational::~Rational()
{
}
void Rational::setNumerator(int a)
{
numerator=a;
}
void Rational::setDenominator(int b)
{
denominator=b;
}
void Rational::Simplify(int numerator,int denominator)
{
int gcd;
int smallest = numerator > denominator ? numerator : denominator;
for(int i=1;i<=smallest;i++)
{
if(numerator%i==0&&denominator%i==0)
gcd=i;
}
setNumerator(numerator/=gcd);
setDenominator(denominator/=gcd);
}
void Rational::rationalNumber()
{
cout << "Rational Number=" << numerator << '/' << denominator << endl;
}
Rational Rational::operator+(const Rational &rhs)
{
Rational temp(numerator,denominator);
temp.numerator=(numerator*rhs.denominator)+(rhs.numerator*denominator);
temp.denominator=denominator*rhs.denominator;
Simplify(temp.numerator,temp.denominator);
rationalNumber();
return Rational(numerator,denominator);
}
Rational Rational::operator-(const Rational &rhs)
{
Rational temp(numerator,denominator);
temp.numerator=(numerator*rhs.denominator)-(rhs.numerator*denominator);
temp.denominator=denominator*rhs.denominator;
Simplify(temp.numerator,temp.denominator);
rationalNumber();
return Rational(numerator,denominator);
}
Rational Rational::operator*(const Rational &rhs)
{
Rational temp(numerator,denominator);
temp.numerator=(numerator*rhs.numerator);
temp.denominator=denominator*rhs.denominator;
Simplify(temp.numerator,temp.denominator);
rationalNumber();
return Rational(numerator,denominator);
}
Rational Rational::operator/(const Rational &rhs)
{
Rational temp(numerator,denominator);
temp.numerator=(numerator*rhs.denominator);
temp.denominator=denominator*rhs.numerator;
Simplify(temp.numerator,temp.denominator);
rationalNumber();
return Rational(numerator,denominator);
}
|