Fractions
For those of you like me that rarely use the C++ floating-point types
(float, double), it often comes as a bit of surprise
when the floating-point representation of a number fails to accurately
capture the value. Certainly double, which is usually stored
as a 64-bit value, is far better than the old float, which is
only 32 bits, but problems do arise. For example:
float n = 2.0;
float d = 3.0;
cout.precision(17);
cout << n / d << endl;
Produces 0.66666668653488159, which is accurate to 8 decimal
places. Not bad, but a bit dirty for a discipline that prides itself
on precision.
A solution that is often used when precision is of greatest importance
and all of the numbers involved are going to be rational (that is,
expressible as a fraction) is to use a custom type that implements
fractions / rational numbers. This is what you will do in this assignment.
The Spec
Implement class Fraction. The interface for Fraction should be
contained in "fraction.h", and the implementation in "fraction.cc".
You must also write a program to demonstrate that you have rigorously
tested your Fraction class, which must be in "main.cc". You
must submit a Makefile for this assignment.
Fraction must have, at minimum, the following methods:
- Default constructor
- Copy constructor
- Assignment operator (operator =)
- Comparison operator (operator ==)
- Addition operator (operator +)
- Subtraction operator (operator -)
- Multiplication operator (operator *)
- Division operator (operator /)
Additionally, bonus credit is available for implementing any or all of
the following methods:
- Comparison operators (operators <, >, !=)
- Conversion operator for ints (allow you to write things like
Fraction a = (Fraction)int)
- Output operator (operator <<)
Extra credit is also available if your fraction is always stored in
"lowest terms." You may want to look at the
Euclidean
Algorithm for help here.
Hints
- Don't have your main.cc include your fraction.cc, it should include
fraction.h and your Makefile should handle the rest.
- Sit down with a piece of paper and remember how to add and
subtract fractions. Those are considerably harder than multiply and divide.
- If any of your methods are getting longer than 5-10 lines of code,
you are probably doing something wrong.
- A great portion of your grade will be based on your main.cc
demonstration of the correctness of your fraction package. Test
thoroughly.
- It doesn't make sense for both numerator and denominator to
be negative. Make sure yours aren't.