1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
|
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
#include"classRats.h"
ratNum::ratNum()
{
//step 1a. create default constructors 0/1
num = 0;
den = 1;
}
ratNum::ratNum(int inNum, int inDen)
{
//step 1a. create user supplied crusntructors using private members num and den
num = inNum;
den = inDen;
}
void ratNum::setNum(int inNum)
{
//step 1b. set num
num = inNum;
}
void ratNum::setDen(int inDen)
{
//step 1b. set den
den = inDen;
}
int ratNum::getNum()
{
//step 1b. get num
return num;
}
int ratNum::getDen()
{
//step 1b. get den
return den;
}
void ratNum::printEm(ofstream& outf)
{
//step 1c. create printEm method
outf << "step 1 C" << endl;
outf << "Numerator = " << num << " Denminator = " << den << endl;
}
ratNum operator +(ratNum a, ratNum b)
{
ratNum c;
c.num = (a.num * b.den) + (b.num * a.den);
c.den = a.den * b.den;
c.reduceEm(c.num, c.den, c);
return c;
}
ratNum operator -(ratNum a, ratNum b)
{
ratNum c;
c.num = (a.num * b.den) - (b.num * a.den);
c.den = a.den * b.den;
c.reduceEm(c.num, c.den, c);
return c;
}
ratNum operator *(ratNum a, ratNum b)
{
ratNum c;
c.num = a.num * b.num;
c.den = a.den * b.den;
c.reduceEm(c.num, c.den, c);
return c;
}
ratNum operator /(ratNum a, ratNum b)
{
ratNum c;
c.num = a.num * b.den;
c.den = a.den * b.num;
c.reduceEm(c.num, c.den, c);
return c;
}
//step 1e. overloaded operators for input and output in format num/den
ostream& operator <<(ostream& ostr, ratNum c)
{
if(c.den == 1)
{
ostr << c.num;
}
else
if(c.den == 0)
{
ostr << "error can't divide by 0" << endl;
}
else
{
ostr << c.num << "/" << c.den;
}
return ostr;
}
istream& operator >>(istream& istr, ratNum &c)
{
char ch;
istr >> ch >> c.num >> ch >> c.den >> ch;
return istr;
}
//step 1f. created reducem function to reduce fractions to lowest form, and properly place -'s
void ratNum::reduceEm(int &num, int &den, ratNum &c)
{
int gcf = abs(c.num) * abs(c.den);
for (gcf; gcf > 1; gcf--)
{
if ((abs(c.den) % gcf == 0) && (abs(c.num) % gcf == 0))
{
c.den /= gcf;
c.num /= gcf;
}
}
if (c.den < 0)
{
c.num *= -1;
c.den *= -1;
}
if (c.num == 0)
{
c.den = 1;
}
}
|