CIT042 Index > Assignment - Objects

Read everything before doing anything

Assignment - Objects

Create a class called Rational for performing arithmetic with fractions. You will write this class to conform to the following specifications.

Methods

Implement the following methods:

Reducing Fractions

To reduce a fraction to its lowest terms, you must divide both the numerator and denominator by their greatest common divisor. Here is code that calculates the greatest common divisor. You should copy and paste this into your Rational class.

sub gcd
{
	my $self = shift;
	my $a = $self->{numerator};
	my $b = $self->{denominator};
	my $mod;

	# ensure that both numbers are positive
	$a = -$a if ($a < 0);
	$b = -$b if ($b < 0);

	# avoid division by zero
	if ($a == 0 || $b == 0)
	{
		$b = 0;
	}
	else
	{
		if ($a < $b)	# a must always be greater than b
		{
			($b, $a) = ($a, $b); # swap them
		}
		while (($mod = $a % $b) != 0)
		{
			$a = $b;
			$b = $mod;
		}
	}
	return $b;
}

Testing your Class

You may download test_rational.pl, a program which lets you enter fractions and operations and see the results. (Enter fractions in the form 2/3.)

When You Finish

Email your file Rational.pm to david.eisenberg@evc.edu. The subject line of your email must include your full name, the class name, and the assignment title. Here are two correct examples:

CIT042 - Jane Bloggs - Objects
Objects program, CIT042, Jane Bloggs