Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- using namespace std;
- class Rational {
- private:
- int _n;
- int _d;
- public:
- Rational(int n = 0, int d = 1) {
- int tmp = _gcd(n, d) * d / abs(d);
- _n = n / tmp;
- _d = d / tmp;
- }
- int numerator() const {
- return _n;
- }
- int denominator() const {
- return _d;
- }
- const Rational& operator+() const {
- return *this;
- }
- const Rational operator-() const {
- return Rational(-_n, _d);
- }
- Rational& operator++() {
- *this += 1;
- return *this;
- }
- Rational operator++(int) {
- Rational copy = *this;
- *this += 1;
- return copy;
- }
- Rational& operator--() {
- *this -= 1;
- return *this;
- }
- Rational operator--(int) {
- Rational copy = *this;
- *this -= 1;
- return copy;
- }
- friend Rational operator+(const Rational& a, const Rational& b);
- friend Rational operator-(const Rational& a, const Rational& b);
- friend Rational operator*(const Rational& a, const Rational& b);
- friend Rational operator/(const Rational& a, const Rational& b);
- friend Rational& operator+=(Rational& a, const Rational& b);
- friend Rational& operator-=(Rational& a, const Rational& b);
- friend Rational& operator*=(Rational& a, const Rational& b);
- friend Rational& operator/=(Rational& a, const Rational& b);
- friend bool operator==(const Rational& a, const Rational& b);
- friend bool operator!=(const Rational& a, const Rational& b);
- private:
- int _gcd(int a, int b) {
- a = abs(a);
- b = abs(b);
- return (a == 0) ? b : _gcd(b % a, a);
- }
- };
- Rational operator+(const Rational& a, const Rational& b) {
- return Rational(a._n * b._d + b._n * a._d, a._d * b._d);
- }
- Rational operator-(const Rational& a, const Rational& b) {
- return Rational(a._n * b._d - b._n * a._d, a._d * b._d);
- }
- Rational operator*(const Rational& a, const Rational& b) {
- return Rational(a._n * b._n, a._d * b._d);
- }
- Rational operator/(const Rational& a, const Rational& b) {
- return Rational(a._n * b._d, a._d * b._n);
- }
- Rational& operator+=(Rational& a, const Rational& b) {
- a = a + b;
- return a;
- }
- Rational& operator-=(Rational& a, const Rational& b) {
- a = a - b;
- return a;
- }
- Rational& operator*=(Rational& a, const Rational& b) {
- a = a * b;
- return a;
- }
- Rational& operator/=(Rational& a, const Rational& b) {
- a = a / b;
- return a;
- }
- bool operator==(const Rational& a, const Rational& b) {
- return (a._n == b._n) & (a._d == b._d);
- }
- bool operator!=(const Rational& a, const Rational& b) {
- return !(a == b);
- }
Add Comment
Please, Sign In to add comment