Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <numeric>
- using namespace std;
- class Rational {
- public:
- Rational() = default;
- Rational(int numerator)
- : numerator_(numerator)
- , denominator_(1)
- {
- }
- Rational(int numerator, int denominator)
- : numerator_(numerator)
- , denominator_(denominator)
- {
- Normalize();
- }
- int Numerator() const {
- return numerator_;
- }
- int Denominator() const {
- return denominator_;
- }
- private:
- void Normalize() {
- if (denominator_ < 0) {
- numerator_ = -numerator_;
- denominator_ = -denominator_;
- }
- int n = gcd(numerator_, denominator_);
- numerator_ /= n;
- denominator_ /= n;
- }
- int numerator_ = 0;
- int denominator_ = 1;
- };
- ostream& operator<<(ostream& output, Rational rational) {
- output << rational.Numerator() << '/' << rational.Denominator();
- return output;
- }
- istream& operator>>(istream& input, Rational& rational) {
- int numerator, denominator;
- char slash;
- input >> numerator >> slash >> denominator;
- rational = Rational{numerator, denominator};
- return input;
- }
- Rational operator+(Rational r1, Rational r2) {
- return {(r1.Numerator()*r2.Denominator())+
- (r2.Numerator()*r1.Denominator()),
- r1.Denominator()*r2.Denominator()};
- }
- Rational operator-(Rational r1, Rational r2) {
- return {(r1.Numerator()*r2.Denominator())-
- (r2.Numerator()*r1.Denominator()),
- r1.Denominator()*r2.Denominator()};
- }
- Rational operator+(Rational r1) {
- return {r1.Numerator(),
- r1.Denominator()};
- }
- Rational operator-(Rational r1) {
- return {-r1.Numerator(),
- r1.Denominator()};
- }
- int main() {
- Rational r1,r2,r;
- cin >> r1 >> r2;
- cout << r1+r2;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement