Advertisement
Alaricy

перегрузка дроби

Dec 7th, 2022
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <numeric>
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <iostream>
  5. #include <map>
  6. #include <set>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10.  
  11. using namespace std;
  12.  
  13. class Rational {
  14. public:
  15.     Rational() = default;
  16.  
  17.     Rational(int numerator)
  18.         : numerator_(numerator)
  19.         , denominator_(1) {
  20.     }
  21.  
  22.     Rational(int numerator, int denominator)
  23.         : numerator_(numerator)
  24.         , denominator_(denominator) {
  25.         Normalize();
  26.     }
  27.  
  28.     int Numerator() const {
  29.         return numerator_;
  30.     }
  31.  
  32.     int Denominator() const {
  33.         return denominator_;
  34.     }
  35.  
  36. private:
  37.     void Normalize() {
  38.         if (denominator_ < 0) {
  39.             numerator_ = -numerator_;
  40.             denominator_ = -denominator_;
  41.         }
  42.         const int divisor = gcd(numerator_, denominator_);
  43.         numerator_ /= divisor;
  44.         denominator_ /= divisor;
  45.     }
  46.  
  47.     int numerator_ = 0;
  48.     int denominator_ = 1;
  49. };
  50.  
  51. ostream& operator<<(ostream& output, Rational MyValue )
  52. {
  53.     output<<MyValue.Numerator()<<"/"<<MyValue.Denominator();
  54.     return output;
  55. }
  56.  
  57.  istream& operator>>(istream& in, Rational& rat){
  58.     int numerator_, denominator_;
  59.     char slash;
  60.     in >>  numerator_ >> slash >> denominator_;
  61.      rat = Rational{numerator_, denominator_};
  62.         return in;
  63.     }
  64.  
  65. int main() {
  66.   Rational r10;
  67.     cin >> r10;
  68.    Rational r1();
  69.     Rational r2(8);
  70.     Rational r3(-8);
  71.     Rational r4(1,2);
  72.     Rational r5(-1,2);
  73.     Rational r6(10,-20);
  74.     Rational r7(-1,-2);
  75.     Rational r8(10,15);
  76.     Rational r9(0,-5);
  77.    
  78.     cout << r10<<endl;
  79.     cout << r7<<endl;
  80.     cout << r8<< endl;
  81.     cout << r9 <<endl;
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement