#include "Rational.h"
#include <iostream.h>
template<class T>
Rational::Rational(T lhs=static_cast<T>(0),T rhs=static_cast<T>(1))
{
if (!rhs) throw("zero error");
above=lhs;
below=rhs;
simple(*this);
changeSign(*this);
}
Rational::Rational(const Rational& rhs)
{
rationCopy(rhs);
simple(*this);
changeSign(*this);
}
Rational::~Rational()
{
}
void Rational::rationCopy(const Rational& rhs)
{
above=rhs.above;
below=rhs.below;
}
void Rational::changeSign(Rational& rhs)
{
if (rhs.below<0){
rhs.above=-rhs.above;
rhs.below=-rhs.below;
}
}
void Rational::simple(Rational&rhs)
{
int a,b,c,i;
a=rhs.above>rhs.below?rhs.above:rhs.below;
b=rhs.above<=rhs.below?rhs.above:rhs.below;
c=0;
i=b+1;
while ((--i>1)&&(!(a%i)&&!(b%i)));
rhs.above/=i;
rhs.below/=i;
}
Rational& Rational::operator =(const Rational &rhs)
{
rationCopy(rhs);
return *this;
}
Rational& Rational::operator +(const Rational& lhs,const Rational& rhs)
{
return Rational(lhs.above*rhs.below+lhs.below*rhs.above,lhs.below*rhs.below);
}
Rational& Rational::operator - (const Rational&lhs,const Rational&rhs)
{
return Rational(lhs.above*rhs.below-lhs.below*rhs.above,lhs.below*rhs.below);
}
Rational& Rational::operator *(const Rational& lhs,const Rational& rhs)
{
return Rational(lhs.above*rhs.above,lhs.below*rhs.below);
}
template<class T>
Rational Rational::operator /(const Rational& lhs,const Rational& rhs)
{
if (!rhs.below)
throw("zero error");
return Rational(lhs.above*rhs.below,lhs.below*rhs.above);
}
template<class T>
const T Rational::getAbove()
{
return above;
}
template<class T>
const T Rational::getBelow()
{
return below;
}
template<class T>
void Rational::print()
{
cout<<above<<'/'<<below<<endl;
}