diff --git a/fractions b/fractions new file mode 100755 index 0000000..f8f63fc Binary files /dev/null and b/fractions differ diff --git a/fractions.cpp b/fractions.cpp new file mode 100644 index 0000000..e3c4798 --- /dev/null +++ b/fractions.cpp @@ -0,0 +1,18 @@ +#include +#include "fractions.hpp" + + +int main() { + int a = 7; + int b = 3; + int c = 1; + int d = 11; + fraction q(a,b); + fraction q2(c,d); + cout << a << "/" << b << '=' << q << endl; + cout << q << "+" << q2 << '=' << q + q2 << endl; + cout << q << "-" << q2 << '=' << q - q2 << endl; + cout << q << "*" << q2 << '=' << q * q2 << endl; + cout << q << "/" << q2 << '=' << q / q2 << endl; + return 0; +} diff --git a/fractions.hpp b/fractions.hpp new file mode 100644 index 0000000..75108f0 --- /dev/null +++ b/fractions.hpp @@ -0,0 +1,69 @@ +#include + +using namespace std; + +class fraction { + private: + int n, d; + int gcd (int a, int b) const { + if (a == 0) { + return b; + } + if (b == 0) { + return a; + } + if (a == b) { + return a; + } + + if (a > b) { + return gcd(a-b, b); + } + + return gcd(a, b-a); + } + public: + // Constructors + fraction(int a, int b) { + int hcf = gcd(a,b); + n = a / hcf; + d = b / hcf; + } + fraction(const fraction &q) { + int hcf = gcd(q.n,q.d); + n = q.n / hcf; + d = q.d / hcf; + } + // Operators + fraction operator+(const fraction &that) { + int numerator = this->n * that.d + that.n * this->d; + int denominator = this->d * that.d; + fraction q(numerator, denominator); + return q; + } + fraction operator-(const fraction &that) { + int numerator = this->n * that.d - that.n * this->d; + int denominator = this->d * that.d; + fraction q(numerator, denominator); + return q; + } + fraction operator*(const fraction &that) { + int numerator = this->n * that.n; + int denominator = this->d * that.d; + fraction q(numerator, denominator); + return q; + } + fraction operator/(const fraction &that) { + fraction a(this->n,this->d); + fraction b(that.d,that.n); + return a * b; + } + friend ostream &operator<<( ostream &os, const fraction &q ) { + if( q.d == q.n) { + os << 1; + } else { + os << q.n << '/' << q.d; + } + return os; + } +}; diff --git a/fractions.hpp.gch b/fractions.hpp.gch new file mode 100644 index 0000000..6f28b29 Binary files /dev/null and b/fractions.hpp.gch differ