CS 3323
Topics in Programming Languages
C++ Assignment 1, Spring 1999
Due April 12, 1999
Write a class RationalNumber or just Rat for short, if you like,
that implements rationals or fractions as a pair of integers.
- Each rational number should be represented as two integers,
the numerator (numer) and the denominator (denom).
Thus the fraction 5/6 would be represented as the pair of
numbers 5 and 6.
- A default constructor should initialize each declared
rational number to 0, which should be 0/1.
- There should be constructors with 1 and with 2 parameters,
to give a/1 and a/b.
- The constructors and other functions should prevent a 0 denominator
and should prevent a negative denominator. Thus the number -2/3
would be represented by the pair of integers -2 and 3.
- You should reduce or simplify rationals by dividing out the
greatest common divisor.
- You should overload operators
+ - * / for the class,
using the algorithms from grade school. (Addition does not
necessarily have to use the least common multiple, but it could
reduce to lowest terms after calculating.)
- You should overload the operators
/TT>< > <= >= != ==
for the class.
- You should overload friend functions << and >>
to do I/O.
The output form should be "17/12". In case the rational number
has 1 for a denominator, output in the form 23,
rather than 23/1
- Provide your own copy constructor and your own overloaded
assignment operator.
- Provide a private member function reduce to reduce a fraction
to lowest terms.
- Exercise your code with some interesting examples, including
at least a code segment or function that will read an integer n
and will calculate the sum, programmed with a loop:
1 - (1/2) + (1/3) - (1/4) + ... + (-1)^(n+1) (1/n)
For n = 20 this will be (155685007/232792560).
Here is an algorithm to calculate the greatest common divisor:
// gcd: calculate greatest common divisor or a and b
// assumes both a and b >= 0
int gcd(int a, int b)
{
if (b == 0) return a;
return gcd(b, a % b);
Here is some additional code that you should use in testing
your program:
Rat x; cout << "x = " << x << endl; // should output "x = 0"
Rat y(23); cout << "y = " << y << endl; // should output "y = 23"
Rat z(1769, 551); cout << "z = " << z << endl; // should output "z = 61/19"
Rat w; w = z + z/w; cout << "w = " << w << endl;
Rat u(-858, -492); cout << "u = " << u << endl;
Rat v(z); cout << "z = " << z << endl;
Here is code for a C++ class implementing Complex numbers that
is similar to what is needed for this assignment:
- complexIO3.h
- complexIO3.cpp
- complex3.cpp
Revision Date: 4/5/99