Skip to content

Instantly share code, notes, and snippets.

@ehgoodenough
Last active December 16, 2015 20:59
Show Gist options
  • Save ehgoodenough/5495980 to your computer and use it in GitHub Desktop.
Save ehgoodenough/5495980 to your computer and use it in GitHub Desktop.
Adding together fractions of different denominators through a bit of operating overloading and cross multiplication.
#include <sstream>
#include <iostream>
using namespace std;
int getGCD(int a, int b)
{
if(a % b == 0)
{
return b;
}
return getGCD(b, a % b);
}
class Fraction
{
private:
int nu, de;
public:
Fraction(int, int);
string toString();
Fraction & operator+=(const Fraction &other);
const Fraction & operator+(const Fraction &other) const;
};
Fraction::Fraction(int nu, int de)
{
this->nu = nu; this->de = de;
}
string Fraction::toString()
{
stringstream sout;
sout << nu << "/" << de;
return sout.str();
}
Fraction & Fraction::operator+=(const Fraction &other)
{
this->nu = this->nu * other.de + this->de * other.nu;
this->de = this->de * other.de;
int gcd = getGCD(this->nu, this->de);
this->nu = this->nu / gcd;
this->de = this->de / gcd;
return *this;
}
const Fraction & Fraction::operator+(const Fraction &other) const
{
return Fraction(*this) += other;
}
int main()
{
Fraction fraction(1,4);
cout << fraction.toString() << endl;
fraction += Fraction(2,3);
cout << fraction.toString() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment