CSC 120A Homework Assignment 6 - Fall 2004

[Course home page]

Due: Friday, October 15, 2004

Assignment: Rational Numbers

Work INDIVIDUALLY on this assignment. It will count as a homework grade

In Java there is no data type for rational numbers (i.e., fractions) such as "1/3", which is simply represented approximately by a finite precision real number (like a double): 0.33333333. In order to work with rational numbers, we need to define our own class, Rational.

In this assignment you are to develop a class for the rational number data type. You can model your Rational class after the Complex example that we went over in class. The following is a sample program that you can use to test your implementation. You should add more test cases as appropriate. Comment out most of the test program at the beginning. You can remove the comments on each line as you finish implementing that feature of the Rational class and wish to start testing it.

public class RationalTester {
    public static void main(String[] args) {
	Rational rA = new Rational(4, 5);           //  rA = 4 / 5
	Rational rB = new Rational(3, -2);          //  rB = -3 / 2

	System.out.println("rA = " + rA);
	System.out.println("rB = " + rB);
	System.out.println("Numerator of rA is " + rA.numerator());
	System.out.println("Denominator of rB is " + rB.denominator());
	System.out.println("rA + rB = " + rA.add(rB));
	System.out.println("rA * rB = " + rA.multiply(rB));
	System.out.println("rA / rB = " + rA.divide(rB));
	System.out.println("1 / rA = " + rA.invert());
	System.out.println("- rB = " + rB.negate());
	System.out.println("rA equals rB? " + rA.equals(rB));
	System.out.println("As a real number, rA = " + rA.doubleValue());
    }
}	 
    

The output of this program is:

> java RationalTester
rA = 4/5
rB = -3/2
Numerator of rA is 4
Denominator of rB is 2
rA + rB = -7/10
rA * rB = -12/10
rA / rB = -8/15
1 / rA = 5/4
- rB = 3/2
rA equals rB? false
As a real number, rA = 0.8
    

Notice the following:

 

Extra credit:

(Only do this after you've finished everything else.) Add another constructor that takes a rational number in string form (like "3/4") and initializes the fields of the object appropriately.

 

Hand in:

Turn in a printed version of your Java files (Rational.java and RationalTester.java) in class on Friday and also upload them to Viking Web.

 



Last modified: Wed Nov 24 12:54:53 EST 2004