NickAndNick

Class Rational (рациональное число)

Mar 23rd, 2020
844
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. class Rational {
  4. public:
  5.     using llong = long long;
  6.     Rational(llong n, llong d) : n_(n), d_(d) {
  7.         reduce_();
  8.     }
  9.     Rational add(const Rational& x) {
  10.         auto n = n_ * x.d_ + d_ * x.n_;
  11.         auto d = d_ * x.d_;
  12.         return Rational(n, d);
  13.     }
  14.     Rational sub(const Rational& x) {
  15.         auto n = n_ * x.d_ - d_ * x.n_;
  16.         auto d = d_ * x.d_;
  17.         return Rational(n, d);
  18.     }
  19.     Rational mul(const Rational& x) {
  20.         auto n = n_ * x.n_;
  21.         auto d = d_ * x.d_;
  22.         return Rational(n, d);
  23.     }
  24.     Rational div(const Rational& x) {
  25.         auto n = n_ * x.d_;
  26.         auto d = d_ * x.n_;
  27.         return Rational(n, d);
  28.     }
  29. private:
  30.     llong n_;
  31.     llong d_;
  32.     void reduce_() {
  33.         auto x = gcd_(n_, d_);
  34.         n_ /= x;
  35.         d_ /= x;
  36.         if (n_ < 0 && d_ < 0) {
  37.             n_ = abs(n_);
  38.             d_ = abs(d_);
  39.         }
  40.     }
  41.     llong gcd_(llong a, llong b) {
  42.         a = abs(a);
  43.         b = abs(b);
  44.         while (a != b) {
  45.             if (a > b) swap(a, b);
  46.             b = b - a;
  47.         }
  48.         return a;
  49.     }
  50.     friend ostream& operator<<(ostream& out, const Rational& x) {
  51.         if (x.n_ < 0 || x.d_ < 0) out << '-';
  52.         out << '(' << abs(x.n_) << ", " << abs(x.d_) << ')';
  53.         return out;
  54.     }
  55. };
  56. int main() {
  57.     Rational a(3, 8);
  58.     Rational b(2, 5);
  59.     auto add = a.add(b);
  60.     auto sub = a.sub(b);
  61.     auto mul = a.mul(b);
  62.     auto div = a.div(b);
  63.     cout
  64.         << a << " + " << b << " = " << add << '\n'
  65.         << a << " - " << b << " = " << sub << '\n'
  66.         << a << " * " << b << " = " << mul << '\n'
  67.         << a << " / " << b << " = " << div << '\n';
  68.     cin.get();
  69. }
Add Comment
Please, Sign In to add comment