Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 26.09.2020, 17:15   #1
Александр222
Пользователь
 
Регистрация: 15.04.2020
Сообщений: 59
Вопрос C++, Класс "Rational", не могу добавить сокращение для дроби

Задача
Рациональная (несократимая) дробь представляется парой целых чисел (а, 6), где а — числитель, Ь — знаменатель. Создать класс Rational для работы с ра-циональными дробями. Обязательно должна быть реализованы операции:
• сложения add, (a, b) + (с, d) = (ad + be, bd)
• вычитания sub, (a, b) - (с, d) = (ad - be, bd)
• умножения mul, (a, b) x (c, d) = (ac, bd)
• деления div, (a>b) / (c, d) = (ad, be);
• сравнения equal, greate, less.
Должна быть реализована приватная функция сокращения дроби reduce

Вопрос: Как можно реализовать приватную функцию сокращения дроби reduce? Код прилагаю, наработки по этому вопросу выделил в комментарии

Rational.h

Код:
#ifndef RATIONAL_H
#define RATIONAL_H

#include <iostream>
#include <sstream>

class Rational {

private:
    int Numerator{};
    int Denominator{};
    
    /*int GetReduced() {

        int nod(int a, int b);
        int mod = 1;

        if (Numerator == 0 && Denominator == 0) return 0;

        Numerator = abs(Numerator);
        Denominator = abs(Denominator);

        if (Numerator == Denominator) return Numerator;

        if (Denominator > Numerator) {
            mod = Numerator;
            Numerator = Denominator;
            Denominator = mod;
        }
        if (Denominator == 0) return Numerator;

        while (mod) {
            mod = Numerator % Denominator;
            if (mod) {
                Numerator = Denominator;
                Denominator = mod;
            }
        }
        return Denominator;
    }*/

public:
    Rational() = default;
    Rational(int Numerator, int Denominator);
    Rational(const Rational& R);

    void SetNumerator();
    void SetDenominator();

    int GetNumerator() const;
    int GetDenominator() const;
    
    friend Rational operator + (const Rational& a, const Rational& b);
    friend Rational operator - (const Rational& a, const Rational& b);
    friend Rational operator * (const Rational& a, const Rational& b);
    friend Rational operator / (const Rational& a, const Rational& b);
    friend bool operator > (const Rational& a, const Rational& b);
    friend bool operator < (const Rational& a, const Rational& b);
    friend bool operator == (const Rational& a, const Rational& b);
    friend bool operator != (const Rational& a, const Rational& b);

    friend std::ostream& operator << (std::ostream& out, const Rational&);
    friend std::istream& operator >> (std::istream& in, Rational&);
};


#endif
Rational.cpp

Код:
#include <iostream>
#include "Rational.h"

Rational::Rational(int Numerator, int Denominator): Numerator(Numerator), Denominator(Denominator) {}
Rational::Rational(const Rational& R): Numerator{ R.Numerator }, Denominator{ R.Denominator } {}

void Rational::SetNumerator(){}
void Rational::SetDenominator(){}

int Rational::GetNumerator() const { return Numerator; }
int Rational::GetDenominator() const { return Denominator; }


/*Rational GetReduced(){
    int gcd = GetGCD(GetNumerator(), GetDenominator());
    int Numerator = GetNumerator() / gcd;
    int Denominator = GetDenominator() / gcd;
    if (Denominator < 0) {
        Numerator = -Numerator;
        Denominator = -Denominator;
    }
    return Rational(Numerator, Denominator);
}*/


double GetGCD(int& a, int& b) {
    int x = std::abs(a);
    int y = std::abs(b);
    while (1) {
        x = x % y;
        if (x == 0) {
            return y;
        }
        y = y % x;
        if (y == 0) {
            return x;
        }
    }
}

Rational operator + (const Rational& a, const Rational& b) {
    return Rational(a.GetNumerator() * b.GetDenominator() + b.GetNumerator() * a.GetDenominator(), a.GetDenominator() * b.GetDenominator());
}

Rational operator - (const Rational& a, const Rational& b) {
    return Rational(a.GetNumerator() * b.GetDenominator() - b.GetNumerator() * a.GetDenominator(), a.GetDenominator() * b.GetDenominator());
}

Rational operator * (const Rational& a, const Rational& b) {
    return Rational(a.GetNumerator() * b.GetNumerator(), a.GetDenominator() * b.GetDenominator());
}

Rational operator / (const Rational& a, const Rational& b) {
    return Rational(a.GetNumerator() * b.GetDenominator(), a.GetDenominator() * b.GetNumerator());
}

/*std::ostream& operator << (std::ostream& out, const Rational& R) {
    Rational reduced = R.GetReduced();
    return out << reduced.GetNumerator() << "/" << reduced.GetDenominator();
}*/

bool operator > (const Rational& a, const Rational& b) { return (a.GetNumerator()/b.GetNumerator()) > (a.GetDenominator()/b.GetDenominator()); }

bool operator < (const Rational& a, const Rational& b) { return (a.GetNumerator() / b.GetNumerator()) < (a.GetDenominator() / b.GetDenominator()); }

bool operator == (const Rational& a, const Rational& b) { return (a.GetNumerator() == b.GetNumerator() && a.GetDenominator() == b.GetDenominator()); }

bool operator != (const Rational& a, const Rational& b) { return !(a == b); }

std::ostream& operator << (std::ostream& out, const Rational& R) { 
    out << "Numerator, Denominator: " << R.Numerator << ", " << R.Denominator;
    return out;
};

std::istream& operator >> (std::istream& in, Rational& R) {
    in >> R.Numerator >> R.Denominator;
    return in;
};

Последний раз редактировалось BDA; 27.09.2020 в 21:03.
Александр222 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
[Delphi] Игра Пятнашки. Помогите пожалуйста добавить окно "Вы выиграли", когда комбинация будет собрана правильно, и добавить кнопку "Новая игра" Аня20 Паскаль, Turbo Pascal, PascalABC.NET 1 02.06.2017 08:12
Нужно пояснить/прокомментировать код программы, или коды функций "Добавить" "Удалить" "Обновить(редактировать" "Поиск" "Период") ZIRASS PHP 4 15.06.2016 14:23
Создать класс "Вентилятор" содержащий в себе классы: "Двигатель", "Контроллер", "Пульт управления" link90 Общие вопросы C/C++ 2 27.03.2016 12:34
Создать класс "Фигура", от него наследованием создать 3 класса ("треугольник", "четырехугольник", "окружность") funnyy Помощь студентам 3 17.10.2012 17:40
Класс "Дроби" JeyKip Общие вопросы C/C++ 7 16.01.2010 23:29