Advertisement
35657

Untitled

Feb 10th, 2024
887
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1.  
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. class Rational {
  7.  
  8. public:
  9.  
  10.     Rational(int numerator, int denominator) {
  11.         numerator_ = numerator;
  12.         denominator_ = denominator;
  13.         Reduction();
  14.     }
  15.  
  16.     void print() {
  17.         cout << numerator_ << '/' << denominator_ << endl;
  18.     }
  19.  
  20.     void addition(const Rational& other) {
  21.         numerator_ = numerator_ * other.denominator_ + other.numerator_ * denominator_;
  22.         denominator_ = denominator_ * other.denominator_;
  23.         Reduction();
  24.     }
  25.  
  26.     void subtraction(const Rational& other) {
  27.         numerator_ = numerator_ * other.denominator_ - other.numerator_ * denominator_;
  28.         denominator_ = denominator_ * other.denominator_;
  29.         Reduction();
  30.     }
  31.  
  32.     void multiplication(const Rational& other) {
  33.         numerator_ *= other.numerator_;
  34.         denominator_ *= other.denominator_;
  35.         Reduction();
  36.     }
  37.  
  38.     void division(const Rational& other) {
  39.         numerator_ *= other.denominator_;
  40.         denominator_ *= other.numerator_;
  41.         Reduction();
  42.     }
  43.  
  44. private:
  45.     int numerator_;
  46.     int denominator_;
  47.  
  48.     void Reduction() { // сокращение дроби
  49.  
  50.         if (denominator_ < 0) {
  51.             numerator_ *= -1;
  52.             denominator_ *= -1;
  53.         }
  54.  
  55.         int x = numerator_ < 0 ? -numerator_ : numerator_;
  56.         int y = denominator_;
  57.  
  58.         while (x != y) {
  59.             if (x > y) {
  60.                 x -= y;
  61.             }
  62.             else {
  63.                 y -= x;
  64.             }
  65.         }
  66.         numerator_ /= x;
  67.         denominator_ /= x;
  68.     }
  69. };
  70.  
  71.  
  72. int main() {
  73.     Rational r1(1, 2);
  74.     Rational r2(3, 4);
  75.     r1.print();
  76.     r2.print();
  77.  
  78.     r1.addition(r2);
  79.     r1.print();
  80.  
  81.     r1.subtraction(r2);
  82.     r1.print();
  83.  
  84.     r1.multiplication(r2);
  85.     r1.print();
  86.  
  87.     r1.division(r2);
  88.     r1.print();
  89. }
  90.  
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement