Last active
August 24, 2017 15:27
-
-
Save alecGraves/9444d56ba49da1ea73b4ea8c07c81f1d to your computer and use it in GitHub Desktop.
Tiny Rational Class MTRE 2610
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
class Rational{ | |
int n, d; //numerator, denominator | |
int gcf(int x, int y, int z){ return y&&(z=x%y) ? gcf(y,z,0) : y;} | |
void r(){int f=gcf(n, d, 0); n/=f; d/=f;} //reduce | |
public: | |
Rational operator+(Rational R){return Rational(n*R.d+d*R.n, d*R.d);} | |
Rational operator-(Rational R){return Rational(n*R.d-d*R.n, d*R.d);} | |
Rational operator*(Rational R){return Rational(n*R.n, d*R.d);} | |
Rational operator/(Rational R){return Rational(n*R.d, d*R.n);} | |
Rational operator+(int i){return Rational(n+d*i, d);} | |
Rational operator-(int i){return Rational(n-d*i, d);} | |
Rational operator*(int i){return Rational(n*i, d);} | |
Rational operator/(int i){return Rational(n, d*i);} | |
int getNumer(){return n;} | |
int getDenom(){return d;} | |
void print(){printf("%d/%d\n", n, d);} | |
Rational() :n(0),d(1) {} | |
Rational(int N, int D) :n(N), d(D) {} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment