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
|
//Michael Ervin - Rational # header
#ifndef H_RATIONAL
#define H_RATIONAL
#include <iostream>
using namespace std;
class rational
{
protected:
double _n, _d;
public:
rational();
rational(double, double );
void setnum(double);
void setden(double);
double getnum();
double getden();
void printrat(ostream&);
friend void redux(rational&);
friend rational operator+ (rational&, rational&);
friend rational operator- (rational&, rational&);
friend rational operator* (rational&, rational&);
friend rational operator/ (rational&, rational&);
friend ostream& operator<< (ostream&, rational&);
friend istream& operator>> (istream&, rational&);
};
rational::rational()
{
_n = 0;
_d = 1;
}
rational::rational(double _num, double _den)
{
_n = _num;
_d = _den;
}
void rational::setnum(double _num){_n = _num;}
void rational::setden(double _den){_d = _den;}
double rational::getnum() {return _n;}
double rational::getden() {return _d;}
void rational::printrat(ostream& _out){_out << "Numerator = " << _n << " and Denominator = " << _d << endl;}
void redux(rational& _temp)
{
double _d, _t = 1;
_d = (_temp._n > _temp._d) ? _temp._d : _temp._n;
if (_d < 0)
_d *= -1;
for (int i = _d; i >= 2; i--)
if (std::fmod(_temp._n, i) == 0 && std::fmod(_temp._d, i) == 0)
if (_t < i)
_t = i;
_temp._n /= _t;
_temp._d /= _t;
if (_temp._d < 0)
{
_temp._n *= -1;
_temp._d *= -1;
}
}
rational operator+ (rational& _left, rational& _right)
{
double _num, _den;
_num = ((_left._n*_right._d)+(_right._n*_left._d));
_den = (_left._d*_right._d);
rational _temp(_num, _den);
redux(_temp);
return _temp;
}
rational operator- (rational& _left, rational& _right)
{
double _num, _den;
_num = ((_left._n*_right._d)-(_right._n*_left._d));
_den = (_left._d*_right._d);
rational _temp(_num, _den);
redux(_temp);
return _temp;
}
rational operator* (rational& _left, rational& _right)
{
rational _temp((_left._n*_right._n),(_left._d*_right._d));
redux(_temp);
return _temp;
}
rational operator/ (rational& _left, rational& _right)
{
rational _temp((_left._n*_right._d),(_left._d*_right._n));
redux(_temp);
return _temp;
}
ostream& operator<< (ostream& _out, rational& _ratobj)
{
if (_ratobj._d == 1)
_out << _ratobj._n;
else if (_ratobj._n == 0)
_out << 0;
else
_out << _ratobj._n << "/" << _ratobj._d;
return _out;
}
//Reads in numbers formatted - N/D
istream& operator>> (istream& _in, rational& _ratobj)
{
char ch;
_in >> _ratobj._n >> ch >> _ratobj._d;
return _in;
}
#endif
|