X hits on this document

# n_oop2.doc - page 6 / 14

56 views

0 shares

6 / 14

int main(){

Rational x(22,7), y(-3, 8), z(x);

cout << "\nx=  "; x.print();

x = x * y;

cout << "\nx=  "; x.print();

x = z;

cout << "\nx=  "; x.print();

x *= y;

cout << "\nx=  "; x.print();

x.reduce(); cout << " x =  "; x.print();

cout << "\n\n\nPress any key to close console window:  ";

char c; cin >> c;

return 0;

}

Rational::Rational (int n, int d) : num (n), den (d){

reduce();

}

Rational::Rational (const Rational& r) : num(r.num), den(r.den){

}

void Rational::print(){

cout << num << '/' << den;

}

Rational& Rational::operator= (const Rational& r){

num = r.num;

den = r.den;

return *this;

}

Rational& Rational::operator*= (const Rational& r){

num = num * r.num;

den = den * r.den;

reduce();

return *this;

}

Rational operator* (const Rational& a, const Rational& b){

Rational r(a.num*b.num, a.den * b.den);

return r;

}

//private functions used to reduce fraction

int Rational::gcd (int j, int k) {

if (k==0) return j; return gcd(k, j%k);

}

void Rational::reduce () {

int g = gcd(num, den); num /= g; den /= g;

}

Output:

x=  22/7

x=  -33/28