Rational+Class+Code

code //Basic Implementation //Possible expansions: // 1) Reduce to lowest term (Implemented in some solutions) // 2) Display improper fractions

using namespace std;
 * 1) include

class Rational{ protected: int num, den;

public: Rational{num=0; den=1;};//Default constructor Rational(int n, int d){num = n; den = d;}; ~Rational{}; void Display{ cout << num << "/" << den << endl; }; void Set_num(int n){num = n; }; void Set_den(int d){den = d; };

Rational ADD(Rational x){ Rational y;  y.num = num*x.den+den*x.num; y.den = den*x.den; return y; };//add

Rational MINUS(Rational x){ Rational y;  y.num = num*x.den-den*x.num; y.den = den*x.den; return y; };//Minus

Rational MULTIPLY(Rational x){ Rational y;  y.num = num*x.num; y.den = den*x.den; return y; };//Multiply

Rational DIVIDE(Rational x){ Rational y;  y.num = num*x.den; y.den = den*x.num; return y; };//Divide

};//Rational

int main{ Rational R1(1,2),R2(1,4),R3(0,1);

cout << "R1 = " ; R1.Display; cout << "R2 = "; R2.Display; cout << "R3 = "; R3.Display;

//Test Add cout<< "\nTesting ADD == \n"; cout << "R3 = R1 + R2" << endl; R3 = R1.ADD(R2); cout << "R1 = " ; R1.Display; cout << "R2 = "; R2.Display; cout << "R3 = "; R3.Display;

//Test MINUS cout<< "\nTesting MINUS == \n"; cout << "R3 = R1 - R2" << endl; R3 = R1.MINUS(R2); cout << "R1 = " ; R1.Display; cout << "R2 = "; R2.Display; cout << "R3 = "; R3.Display;

//Test Multiply cout<< "\nTesting MULTIPLY == \n"; cout << "R3 = R1 * R2" << endl; R3 = R1.MULTIPLY(R2); cout << "R1 = " ; R1.Display; cout << "R2 = "; R2.Display; cout << "R3 = "; R3.Display;

//Test DIVIDE cout<< "\nTesting DIVIDE == \n"; R3 = R1.DIVIDE(R2); cout << "R3 = R1/R2" << endl; cout << "R1 = " ; R1.Display; cout << "R2 = "; R2.Display; cout << "R3 = "; R3.Display;

system("pause"); return 0; } code