Category : Files from Magazines
Archive   : CUJ9201.ZIP
Filename : 1001098D

 
Output of file : 1001098D contained in archive : CUJ9201.ZIP


Listing 11

//
// rational.cpp
//
#include
#include "rational.h"

rational &rational::operator+=(rational r)
{
num = num * r.denom + r.num * denom;
denom *= r.denom;
simplify();
return *this;
}

rational &rational::operator-=(rational r)
{
num = num * r.denom - r.num * denom;
denom *= r.denom;
simplify();
return *this;
}

rational &rational::operator*=(rational r)
{
num *= r.num;
denom *= r.denom;
simplify();
return *this;
}

rational &rational::operator/=(rational r)
{
num *= r.denom;
denom *= r.num;
simplify();
return *this;
}

rational rational::operator+(rational r)
{
rational result(*this);
return result += r;
}

rational rational::operator-(rational r)
{
rational result(*this);
return result -= r;
}

rational rational::operator*(rational r)
{
rational result(*this);
return result *= r;
}

rational rational::operator/(rational r)
{
rational result(*this);
return result /= r;
}

void rational::put(FILE *f)
{
fprintf(f, "(%ld/%ld)", num, denom);
}

long gcd(long x, long y)
{
x = labs(x);
y = labs(y);
while (x != y)
{
if (x < y)
y -= x;
if (y < x)
x -= y;
}
return x;
}

void rational::simplify()
{
long x = gcd(num, denom);
num /= x;
denom /= x;
}