Alternative Lab 11

Goals

To understand and use techniques for programming in C++.

Rational numbers

Rational numbers are numbers that can be represented by a ratio of two integers. So 19/5, 2/3, -5/6 and 7/1 are all rational numbers (note that whole numbers have a divisor of 1). Your task is to write a class called Rational that implements arithmetic with rational numbers. Your class should include overloaded operators for +, -, * and /. In addition, it should also overload the << output operator so that rational numbers may be printed to the output, and ==, > and < for comparison.

A Test Program

Use the following main function to test your class. Your class must work with this code, without alteration.

int main()   {
     // object creation
     Rational r1, r2(5,6), r3(19,5);
     // output
     cout << "r1 is " << r1 << endl;
     cout << "r2 is " << r2 << endl;
     cout << "r3 is " << r3 << endl;
     // addition
     r1 = r2 + r3;
     cout << "r2 + r3 = " << r1 << endl;
     // subtraction
	  r1 = r2 - r3;
     cout << "r2 - r3 =" << r1 << endl;
     // multiplication
	  r1 = r2 * 32;
     cout << "r2 * r3 =" << r1 << endl;
	  // division
     r1 = r2 / r3;
     cout << "r2 / r3 =" << r1 << endl;
	  // comparision
     if (r3 > r2)
       cout << "r3 > r2" << endl;
     else
       cout << "r3 <= r2" << endl;
     return 0;
 }

Hints
1. Rational numbers may be negative so make sure your arithmetic operators do not make assumptions of positivity, OR you may want to
store the sign of the rational number separately.

2. Some results are "improper" in that they can be simplified. e.g. 1/4 + 1/4 = 2/4, but should be 1/2. You can use the gcd algorithm to do
the simplification. gcd is:

int gcd(int a, int b) {
  int t;
  while (b != 0) {
    t = a % b;
    a = b;
    b = t;
  }
  return a;
}

This assumes that a >= b >= 0. You should make gcd a private static member function of Rational.

3. Overloading the << operator is achived with a global function with the signature:

ostream& operator<<(ostream& sout, const Rational &obj)

The body of the function uses standard output of built-in types using the stream sout. i.e. the two parts of the rational number,
with a / between them. The function should return the stream sout when it is done. Your class for Rational should declare this
function as a friend so that it can access the data members of the class directly:

friend ostream& operator<<(ostream& sout, const Rational &obj);
Deliverables

A single file with the source code of your class and the above test main function, and results of running the test appended ina C-style comment (i.e. between /* .. */). The file should be submitted using the assignment submitter.

Due Date

This assignment is due on Monday May 1st. before 5:00pm. Please use the file submission page to submit your electronic copy.