35657

Untitled

Nov 11th, 2023
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Fraction {
  6.  
  7. public:
  8.  
  9.     Fraction() : Fraction(1, 1) {}
  10.  
  11.     Fraction(int num, int denom) : numerator(num), denominator(denom) {}
  12.  
  13.     Fraction(const Fraction& fract) : numerator(fract.numerator), denominator(fract.denominator) {}
  14.  
  15.     Fraction& operator+=(const Fraction& other) {
  16.         numerator = numerator * other.denominator + denominator * other.numerator;
  17.         denominator *= other.denominator;
  18.         Reduction();
  19.         return *this;
  20.     }
  21.  
  22.     Fraction& operator-=(const Fraction& other) {
  23.         numerator = numerator * other.denominator - denominator * other.numerator;
  24.         denominator *= other.denominator;
  25.         Reduction();
  26.         return *this;
  27.     }
  28.  
  29.     Fraction& operator*=(const Fraction& other) {
  30.         numerator *= other.numerator;
  31.         denominator *= other.denominator;
  32.         Reduction();
  33.         return *this;
  34.     }
  35.  
  36.     Fraction& operator/=(const Fraction& other) {
  37.         numerator *= other.denominator;
  38.         denominator *= other.numerator;
  39.         Reduction();
  40.         return *this;
  41.     }
  42.  
  43.     ~Fraction() {}
  44.  
  45.     void print() {
  46.         std::cout << numerator << " / " << denominator << std::endl;
  47.     }
  48.  
  49. private:
  50.     void Reduction() {
  51.         int x = numerator;
  52.         int y = denominator;
  53.  
  54.         while (x != y) {
  55.             if (x > y) {
  56.                 x = x - y;
  57.             }
  58.             else {
  59.                 y = y - x;
  60.             }
  61.         }
  62.         numerator /= x;
  63.         denominator /= x;
  64.     }
  65.  
  66.     int numerator;
  67.     int denominator;
  68. };
  69.  
  70. Fraction& operator+(const Fraction& left, const Fraction& right) {
  71.     Fraction temp = left;
  72.     temp += right;
  73.     return temp;
  74. }
  75.  
  76.  
  77. int main() {
  78.     Fraction a(1,2);
  79.    
  80.     Fraction b(3,4);
  81.  
  82.     a += b;
  83.     a.print();
  84.  
  85.     a -= b;
  86.     a.print();
  87.  
  88.     a *= b;
  89.     a.print();
  90.  
  91.     a /= b;
  92.     a.print();
  93.  
  94.     Fraction c = a + b;
  95.  
  96.     c.print();
  97. }
Advertisement
Add Comment
Please, Sign In to add comment