Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "rat.h"
- #include <sstream>
- // These functions can be useful for calculations with fractions
- rat::rat() : num(0),den(1)
- {
- }
- rat::rat(int n):num(n),den(1)
- {
- }
- rat::rat(int n, int d):num(n),den(d)
- {
- if(den==0)
- {
- num=0;
- den=1;
- }
- reduce();
- }
- int gcd(int x, int y)
- {
- if (y == 0)
- return x;
- return gcd(y, x % y);
- }
- int lcm(int x, int y)
- {
- return (x * y) / gcd(x, y);
- }
- int rat::getNum() const
- {
- return num;
- }
- int rat::getDen() const
- {
- return den;
- }
- void rat::reduce()
- {
- int g = gcd(num, den);
- num /= g;
- den /= g;
- if(den < 0)
- {
- num = -num;
- den = -den;
- }
- }
- rat rat::reciprocal() const
- {
- rat result(den,num);
- return result;
- }
- rat rat::operator+(const rat& right) const
- {
- rat result;
- result.den = den * right.den;
- result.num = (num * right.den) + den * right.num;
- result.reduce();
- return result;
- }
- rat rat::operator-(const rat& right) const
- {
- rat result;
- result.den = den * right.den;
- result.num = (num * right.den) - den * right.num;
- result.reduce();
- return result;
- }
- rat rat::operator*(const rat& right) const
- {
- rat result;
- result.den = den * right.den;
- result.num = (num * right.num);
- result.reduce();
- return result;
- }
- rat rat::operator/(const rat& right) const
- {
- rat result;
- result.den = den * right.num;
- result.num = num*right.den;
- result.reduce();
- return result;
- }
- bool rat::operator==(const rat& right) const
- {
- rat r = (*this) - right;
- return r.num == 0 && r.den ==1;
- }
- bool rat::operator!=(const rat& right) const
- {
- rat r = (*this) - right;
- return !((*this)==right);
- }
- bool rat::operator<(const rat& right) const
- {
- rat r = (*this) - right;
- r.reduce();
- return r.num<0;
- }
- bool rat::operator>(const rat& right) const
- {
- rat r = (*this) - right;
- r.reduce();
- return r.num>0;
- }
- bool rat::operator<=(const rat& right) const
- {
- return ((*this)<right || (*this) == right);
- }
- bool rat::operator>=(const rat& right) const
- {
- return ((*this)>right || (*this) == right);
- }
- std::string rat::str() const
- {
- std::stringstream s;
- s<<num<<"/"<<den;
- return s.str();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement