/
khazov
/
module2
Обзор
Документация
Войти
/
khazov
/
module2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
task8_1/Fraction.cpp
132 строки
3 KB
HazovAV
добавлены решения по задачам
29 июл 2026, 14:44
29 июл 2026, 14:44
c6ff9de
Код
Авторство
О чём код?
#include "Fraction.h" #include <sstream> #include <cmath> // ����������� ������� ��� ���������� ��� (���� ��� std::gcd) int Fraction::gcd(int a, int b) { a = std::abs(a); b = std::abs(b); while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } Fraction::Fraction(int numerator, int denominator) { if (denominator == 0) { throw std::invalid_argument("Denominator cannot be zero"); } num_ = numerator; den_ = denominator; normalize(); } void Fraction::normalize() { // ��������� �����: ���� ������ �������� � ��������� if (den_ < 0) { num_ = -num_; den_ = -den_; } // ���������� ����� int common = gcd(num_, den_); if (common != 0) { num_ /= common; den_ /= common; } } bool Fraction::operator==(const Fraction& other) const { return num_ == other.num_ && den_ == other.den_; } bool Fraction::operator!=(const Fraction& other) const { return !(*this == other); } bool Fraction::operator<(const Fraction& other) const { // ��������� ����� ����� �����������: a/b < c/d <=> a*d < c*b long long lhs = static_cast<long long>(num_) * other.den_; long long rhs = static_cast<long long>(other.num_) * den_; return lhs < rhs; } bool Fraction::operator>(const Fraction& other) const { return other < *this; } bool Fraction::operator<=(const Fraction& other) const { return !(other < *this); } bool Fraction::operator>=(const Fraction& other) const { return !(*this < other); } Fraction Fraction::operator+(const Fraction& other) const { int newNum = num_ * other.den_ + other.num_ * den_; int newDen = den_ * other.den_; return Fraction(newNum, newDen); } Fraction Fraction::operator-(const Fraction& other) const { int newNum = num_ * other.den_ - other.num_ * den_; int newDen = den_ * other.den_; return Fraction(newNum, newDen); } Fraction Fraction::operator*(const Fraction& other) const { int newNum = num_ * other.num_; int newDen = den_ * other.den_; return Fraction(newNum, newDen); } Fraction Fraction::operator/(const Fraction& other) const { if (other.num_ == 0) { throw std::invalid_argument("Division by zero fraction"); } int newNum = num_ * other.den_; int newDen = den_ * other.num_; return Fraction(newNum, newDen); } Fraction& Fraction::operator++() { // ++f: f = f + 1 num_ += den_; return *this; } Fraction Fraction::operator++(int) { Fraction old = *this; ++(*this); return old; } Fraction& Fraction::operator--() { // --f: f = f - 1 num_ -= den_; return *this; } Fraction Fraction::operator--(int) { Fraction old = *this; --(*this); return old; } Fraction Fraction::operator-() const { return Fraction(-num_, den_); } std::string Fraction::dump() const { std::ostringstream oss; if (den_ == 1) { oss << num_; } else { oss << num_ << "/" << den_; } return oss.str(); }