Добавил:
vvrstcnho
Рад, если кому-то помог
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабораторные работы С++ (для ИВТ) / Готовые лабы С++ / Лаба4 / Laba 4 (4)
.cpp#include <iostream>
#include <locale>
#include <cmath>
using namespace std;
class rational {
int numerator;
int denominator;
void reduce() {
int gcd_val = gcd(abs(numerator), abs(denominator));
numerator /= gcd_val;
denominator /= gcd_val;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
int gcd(int a, int b) const {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public:
// Конструктор (может использоваться как конструктор преобразования)
rational(int num = 0, int den = 1) : numerator(num), denominator(den) {
if (denominator == 0) denominator = 1;
reduce();
}
// Арифметические операции
rational operator+(const rational& other) const {
return rational(numerator * other.denominator + other.numerator * denominator,
denominator * other.denominator);
}
rational operator-(const rational& other) const {
return rational(numerator * other.denominator - other.numerator * denominator,
denominator * other.denominator);
}
rational operator*(const rational& other) const {
return rational(numerator * other.numerator,
denominator * other.denominator);
}
rational operator/(const rational& other) const {
return rational(numerator * other.denominator,
denominator * other.numerator);
}
// Операции с целыми числами
friend rational operator+(const rational& r, int n);
friend rational operator+(int n, const rational& r);
// Операции сравнения
bool operator==(const rational& other) const {
return numerator == other.numerator && denominator == other.denominator;
}
bool operator<(const rational& other) const {
return numerator * other.denominator < other.numerator * denominator;
}
// Приведение к double
operator double() const {
return static_cast<double>(numerator) / denominator;
}
void print() const {
cout << numerator << "/" << denominator;
}
};
rational operator+(const rational& r, int n) {
return r + rational(n);
}
rational operator+(int n, const rational& r) {
return rational(n) + r;
}
int main() {
setlocale(LC_ALL, "ru_RU.UTF-8");
rational r1(2, 3);
rational r2(1, 4);
cout << "r1 = "; r1.print(); cout << endl;
cout << "r2 = "; r2.print(); cout << endl;
rational sum = r1 + r2;
cout << "Сумма: "; sum.print(); cout << endl;
rational prod = r1 * r2;
cout << "Произведение: "; prod.print(); cout << endl;
cout << "r1 как double: " << static_cast<double>(r1) << endl;
// Конструктор преобразования
rational r3 = 5; // int -> rational
cout << "r3 = "; r3.print(); cout << endl;
return 0;
}
Соседние файлы в папке Лаба4
