#include "rationalNumber.h"
#include <iostream>
usingnamespace std;
rationalNumber::rationalNumber(int num, int den) : numerator(num), denominator(den){
}
/*
rationalNumber operator+(rationalNumber c){
rationalNumber temp;
temp.numerator = (numerator * c.denominator) + (c.numerator * denominator);// adds numerator
temp.denominator = denominator * c.denominator;// add denominator
temp.reduction();
return temp;
}
*/
rationalNumber rationalNumber::addition(rationalNumber c){
rationalNumber temp;
temp.numerator = (numerator * c.denominator) + (c.numerator * denominator);// adds numerator
temp.denominator = denominator * c.denominator;// add denominator
temp.reduction();
return temp;
}
rationalNumber rationalNumber::subtraction(rationalNumber c){
rationalNumber temp;
temp.numerator = (numerator * c.denominator) - (c.numerator * denominator);// adds numerator
temp.denominator = denominator * c.denominator;// add denominator
temp.reduction();
return temp;
}
rationalNumber rationalNumber::multiplication(rationalNumber c){
rationalNumber temp;
temp.numerator = numerator * c.numerator; // multiplies numerator
temp.denominator = denominator * c.denominator; // multiplies denominator
temp.reduction();
return temp;
}
rationalNumber rationalNumber::division(rationalNumber c){
rationalNumber temp;
temp.numerator = numerator * c.denominator; // divides numerator and denominator
temp.denominator = denominator * c.numerator; // divdes denominator and numerator
temp.reduction();
return temp;
}
void rationalNumber::printRational(){
cout <<numerator << "/" <<denominator;
}
void rationalNumber::printRationalAsDouble(){
cout << (double) numerator / denominator;
}
void rationalNumber::reduction()
{
int largest; // initializes largest
largest = numerator > denominator ? numerator : denominator;
int gcd = 1; // greatest common divisor
for ( int loop = 2; loop <= largest; loop++ ) // initializes loop to 2, if loop is less that or equal to the largest, then increment the loop counter.
if ( numerator % loop == 0 && denominator % loop == 0 ) //if the loop's remainder equals 0 and the denominator's remainder equals 0,
gcd = loop; // then the greatest common denominator is assigned the value of the loop.
if (gcd != 0) { // if the greatest common denominator does not equal 0, the divide both the numerator and the denominator by the greatest common denominator.
numerator /= gcd;
denominator /= gcd;
} // end if
} // end function reduction
The assignment that I have is, that I have to create a program that can calculate rational numbers using the overloaded operators. I.e. +, - etc. This program works perfectly, but I need it to use operators, rather than functions if that makes sense.