next up previous
Next: Calculating GCDs Up: Assignment 9: Homemade Objects Previous: Another constructor

Modifers and functions

1.
Write a new method called negate that reverses the sign of a rational number. This method should be a modifier, so it should return void. Add lines to main to test the new method.

2.
Write a method called invert that inverts the number by swapping the numerator and denominator. Remember the swap pattern we have seen before. Add lines to main to test the new method.

3.
Write a method called toDouble that converts the rational number to a double (floating-point number) and returns the result. This method is a pure function; it does not modify the object. As always, test the new method.

4.
Write a modifier named reduce that reduces a rational number to its lowest terms by finding the GCD of the numerator and denominator and then dividing top and bottom by the GCD.

You may want to write a method called commonDivisor that finds the greatest common divisor of the numerator and the denominator. The next section explains an algorithm for finding the GCD. This method should be a pure function; it should not modify the instance variables of the object on which it is invoked.

5.
Write a method called add that takes two Rational numbers as arguments and returns a new Rational object. The return object, not surprisingly, should contain the sum of the arguments.

There are several ways to add fractions. You can use any one you want, but you should make sure that the result of the operation is reduced so that the numerator and denominator have no common divisor (other than 1).


next up previous
Next: Calculating GCDs Up: Assignment 9: Homemade Objects Previous: Another constructor
Allen B. Downey
1999-11-02