Rational arithmetic

Object

To test understanding of constructors, and the use of operator overloading. To explore program testing concepts.

Task description

Outline

Write a program to emulate rational (fractional) arithmetic, by defining a class that represents the type 'rational'. An example of how to do this for a point in XY space is on pages 222 - 231 of the text. Your class should encapsulate the parts of a fraction (use long integers) and contain the following functions:

  1. an inline constructor with use of the member initialization list and appropriate default arguments.
  2. an inline copy constructor.
  3. an overloaded assignment operator.
  4. an overloaded insertion (<<) operator to print the fraction in its simplest form. See page 257 - 260 for an example of how to overload a global operator function that takes a stream as one argument. For instance, the operation 9/8 + 3/8 produces 12/8, but you will want to print this as 3/2. You can use this version of gcd to find the largest common factor of two integers:
    long gcd(long x, long y) {
       return (x == 0) ? y : gcd(y % x, x);
    }
  5. operator overloading functions for addition, subtraction, multiplication and division of fractions. Use the standard +, -, *, / operators for these.

Your test program should show how the operators work for sufficient examples to throughly exercise all the operations. Watch for divide by zero and overflow problems if you can.

Compiler

Use g++. Typing `g++' followed by the file-name containing the source code will compile the program into an executable called a.out. You can also rename the executable using the -o option, or, by creating a file called 'Makefile' (in the same directory as your source file) containing the lines:

LDLIBS = -lm -lg++
CCC = g++

you can simply type `make myfile', where `myfile.cc' is your C++ source file.

Input

Generate all the examples internally in the program. It is not necessary to read values from a file or standard input. Your choice of test examples should follow the guidelines in the handout 'Testing C++ Programs".

Output

Use the overloaded operator <<, which will normally write to the screen, and then redirect the program's output to a file using the method on page 58 of the text. Printing this file on he lineprinter will give a hard copy of the output. A sample output might be:

Add 2/3 and 1/6 : 5/6

Sub 4/2 and 2/2 : 1

Add 9/8 and 3/8: 3/4

Mul 2 and 0/0: error!

etc.

Due date

March 25th., in class. E-mail your completed source code to Heather Pfeiffer (login 'hdp'). Hand in the hard copy version, with a hard copy version of the program output to RTH. [If you are using a PC, we can read 3.5" floppies in standard DOS format.]