In this lab you will write a class for fractions, where a fraction is of the form a / b, where a and b are integers and b != 0. To store a fraction, we will store the numerator a and the denominator b.
Given two fractions a / b and c / d, the arithmetic operations are defined by the following rules:
To compare two fractions a / b and c / d, compare ad and bc. For any relational operator op, if ad op bc, then a / b op c / d. For example, if ad <= bc then a / b <= c / d.
Create a class for fractions that includes the arithmetic operations and the six relational operators (==, != <, <=, >, >=). Your class should include a default constructor, an initializing constructor, and a copy constructor. In addition, create overloaded I/O operators for inputting and outputting fractions.
Remember that when you write your arithmetic operators you want them to work like the built in operators. What does that mean about the return type of your operators? Will the operators modify the invoking object and/or the parm? Think about how the built in operators work to answer these questions.
When a fraction is stored, it should be stored in reduced form, that is, where the greatest common divisor (GCD) of a and b is 1. For example, 3 / 5 is in reduced form, where 18 / 30 is not, because the GCD of 18 and 30 is 6. To reduce a fraction, calculate the GCD and if the GCD is greater than one, divide the numerator and denominator by the GCD. To calculate the GCD, use the iterative version of Euclid's algorithm:
GCD(a,b): while (b != 0) { c = a % b a = b b = c } GCD = a
To reduce your fractions, create a private member function which will convert the invoking object to reduced form. Use this function to reduce the result of each arithmetic operation before it is returned.
Write a main function to test your fraction class. Your main should:
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2002