Homework 7 Csc309.
Due Monday May 15, 2006 by 11:59pm.
Problem 1
25 points.
To receive full credit you must demonstrate your methods. Work incrementally, that is after you write a method test it.
Write a class called Fraction to represent Fractions. Numbers of the form a / b where a and b are integers, a is called the numberator b is the denominator which cannot be zero.
In addition to the two int private data members, provide the following methods and global functions
Class methods:
Fraction() The number 0 where denominator is 1. Fraction(int num) convert constructor to represent a real number, denominator becomes 1 Fraction(int num, int den) Remember denominator cannot be 0 int getNumerator() const int getDenominator() const void reduce() void standardize() When applied should make denominator positive. EXAMPLE 2/-3 ==> -2/3 -2/-3 ==> 2/3 double decimal() returns the number as a decimal.
The following should be global
Fraction operator+(const Fraction& f1, const Fraction& f2) Fraction operator-(const Fraction& f1, const Fraction& f2) Fraction operator*(const Fraction& f1, const Fraction& f2) Fraction operator/(const Fraction& f1, const Fraction& f2) bool operator==(const Fraction& f1, const Fraction& f2) bool operator!=(const Fraction& f1, const Fraction& f2) bool operator<(const Fraction& f1, const Fraction& f2) bool operator<=(const Fraction& f1, const Fraction& f2) bool operator>(const Fraction& f1, const Fraction& f2) bool operator>=(const Fraction& f1, const Fraction& ostream& operator<<(ostream& out, const Fraction& f); istream& operator>>(istream& out, const Fraction& f);
Notes on the methods and functions:
- Arithmetic operations on fractions are defined by the following rules:
- a / b + c / d = (ad + bc) / bd
- a / b - c / d = (ad - bc) / bd
- a / b * c / d = ac / bd
- (a / b) / (c / d) = ad / bc (where c/d is not 0)
- Relational operators should be obvious, after understanding the arithmetic operations.
- The reduce() method modifies the calling object to a reduced form.
For example, 10/15 ==> 2/3.
To write this method, you will need to find the greatest common divisor (gcd) of the numerator and denominator. You are welcome to use the following. You can put it in Fraction.int Fraction::gcd(int a, int b) const { if (b == 0) return a; else return gcd(b, a % b); }
- The output operator (<<) should print the fraction as "a/b"