CS 13A

Dr. Sturm                     HW #8 – class Ratio

 

 

//class Ratio                                                                           

//Write methods operator+, operator-, operator/, and reduce.

//Test each one separately.

//Hand in the completed class Ratio together with the main function that tests each method

#include <string.h>

#include <iostream.h>

#include <conio.h>

class Ratio{

private:

            int num;

            int den;

public:

            Ratio(int n=0,int d=1);

            void setRatio(int n,int d);

            void reduce();

            Ratio invert();

            Ratio operator+(Ratio op2);

            Ratio operator-(Ratio op2);

            Ratio operator*(Ratio op2);

            Ratio operator/(Ratio op2);

            void display();

};

 

Ratio::Ratio(int n,int d){

            num=n;

            den=d;

}

 

void Ratio::setRatio(int n,int d){

            num=n;

            den=d;

}

 

void Ratio::reduce(){

            //This method reduces the Ratio

            //For example, if r1=4/6, then after

            // r1.reduce(), Ratio r1 will be equal

            //to 2/3. 

}//end reduce

 

void Ratio::display(){

            if(den!=1)

                        cout<<num<<"/"<<den<<endl;

            else

                        cout<<num<<endl;

}//end print

 

Ratio Ratio::invert(){

            Ratio temp;

            temp.num=den;

            temp.den=num;

            return(temp);

}//end invert

 

Ratio Ratio::operator*(Ratio op2){

            Ratio result;

            result.num=num*op2.num;

            result.den=den*op2.den;

            result.reduce();

            return(result);

}