using System;
using System.Collections.Generic;
// Абстрактный класс Pair (пара значений)
public abstract class Pair
{
// Пара значений
protected double First { get; set; }
protected double Second { get; set; }
// Конструктор
public Pair(double first, double second)
{
First = first;
Second = second;
}
// Виртуальные арифметические операции
public virtual Pair Add(Pair other)
{
return null; // Будет переопределено в производных классах
}
public virtual Pair Subtract(Pair other)
{
return null; // Будет переопределено в производных классах
}
public virtual Pair Multiply(Pair other)
{
return null; // Будет переопределено в производных классах
}
public virtual Pair Divide(Pair other)
{
return null; // Будет переопределено в производных классах
}
// Метод вывода на экран
public abstract void Display();
}
// Класс Money (деньги)
public class Money : Pair
{
// Конструктор
public Money(int rubles, int kopecks) : base(rubles, kopecks)
{
// Нормализация копеек, если они превышают 99
NormalizeValues();
}
private void NormalizeValues()
{
// Если копейки превышают 99, преобразуем их в рубли
if (Second >= 100)
{
First += (int)(Second / 100);
Second = Second % 100;
}
}
// Геттеры для рублей и копеек
public int Rubles => (int)First;
public int Kopecks => (int)Second;
// Переопределение арифметических операций
public override Pair Add(Pair other)
{
if (other is Money money)
{
int newRubles = Rubles + money.Rubles;
int newKopecks = Kopecks + money.Kopecks;
return new Money(newRubles, newKopecks);
}
throw new ArgumentException("Невозможно сложить разные типы");
}
public override Pair Subtract(Pair other)
{
if (other is Money money)
{
// Преобразование в общие копейки для упрощения расчета
int totalKopecks1 = Rubles * 100 + Kopecks;
int totalKopecks2 = money.Rubles * 100 + money.Kopecks;
int resultKopecks = totalKopecks1 - totalKopecks2;
// Обработка отрицательных значений
if (resultKopecks < 0)
{
throw new ArgumentException("Результат не может быть отрицательным");
}
int newRubles = resultKopecks / 100;
int newKopecks = resultKopecks % 100;
return new Money(newRubles, newKopecks);
}
throw new ArgumentException("Невозможно вычесть разные типы");
}
public override Pair Multiply(Pair other)
{
if (other is Money money)
{
// Преобразование в общие копейки для упрощения расчета
double totalKopecks1 = Rubles * 100 + Kopecks;
double totalKopecks2 = money.Rubles * 100 + money.Kopecks;
double resultKopecks = (totalKopecks1 * totalKopecks2) / 100;
int newRubles = (int)(resultKopecks / 100);
int newKopecks = (int)(resultKopecks % 100);
return new Money(newRubles, newKopecks);
}
throw new ArgumentException("Невозможно умножить разные типы");
}
public override Pair Divide(Pair other)
{
if (other is Money money)
{
// Преобразование в общие копейки для упрощения расчета
double totalKopecks1 = Rubles * 100 + Kopecks;
double totalKopecks2 = money.Rubles * 100 + money.Kopecks;
if (totalKopecks2 == 0)
{
throw new DivideByZeroException("Деление на ноль невозможно");
}
double resultKopecks = (totalKopecks1 / totalKopecks2) * 100;
int newRubles = (int)(resultKopecks / 100);
int newKopecks = (int)(resultKopecks % 100);
return new Money(newRubles, newKopecks);
}
throw new ArgumentException("Невозможно разделить разные типы");
}
// Переопределение метода вывода
public override void Display()
{
Console.WriteLine($"{Rubles} руб. {Kopecks} коп.");
}
}
// Класс Complex (комплексное число)
public class Complex : Pair
{
// Конструктор
public Complex(double real, double imaginary) : base(real, imaginary)
{
}
// Геттеры для действительной и мнимой частей
public double Real => First;
public double Imaginary => Second;
// Переопределение арифметических операций
public override Pair Add(Pair other)
{
if (other is Complex complex)
{
double newReal = Real + complex.Real;
double newImaginary = Imaginary + complex.Imaginary;
return new Complex(newReal, newImaginary);
}
throw new ArgumentException("Невозможно сложить разные типы");
}
public override Pair Subtract(Pair other)
{
if (other is Complex complex)
{
double newReal = Real - complex.Real;
double newImaginary = Imaginary - complex.Imaginary;
return new Complex(newReal, newImaginary);
}
throw new ArgumentException("Невозможно вычесть разные типы");
}
public override Pair Multiply(Pair other)
{
if (other is Complex complex)
{
// (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
double newReal = Real * complex.Real - Imaginary * complex.Imaginary;
double newImaginary = Real * complex.Imaginary + Imaginary * complex.Real;
return new Complex(newReal, newImaginary);
}
throw new ArgumentException("Невозможно умножить разные типы");
}
public override Pair Divide(Pair other)
{
if (other is Complex complex)
{
// (a + bi) / (c + di) = ((ac + bd) / (c^2 + d^2)) + ((bc - ad) / (c^2 + d^2))i
double denominator = complex.Real * complex.Real + complex.Imaginary * complex.Imaginary;
if (denominator == 0)
{
throw new DivideByZeroException("Деление на ноль невозможно");
}
double newReal = (Real * complex.Real + Imaginary * complex.Imaginary) / denominator;
double newImaginary = (Imaginary * complex.Real - Real * complex.Imaginary) / denominator;
return new Complex(newReal, newImaginary);
}
throw new ArgumentException("Невозможно разделить разные типы");
}
// Переопределение метода вывода
public override void Display()
{
if (Imaginary >= 0)
{
Console.WriteLine($"{Real} + {Imaginary}i");
}
else
{
Console.WriteLine($"{Real} - {Math.Abs(Imaginary)}i");
}
}
}
// Класс Series (набор)
public class Series
{
// Список для хранения объектов
private List<Pair> items;
// Конструктор
public Series()
{
items = new List<Pair>();
}
// Добавление элемента в набор
public void Add(Pair item)
{
items.Add(item);
}
// Вывод всех элементов набора
public void DisplayAll()
{
for (int i = 0; i < items.Count; i++)
{
Console.Write($"Элемент {i + 1}: ");
items[i].Display();
}
}
// Получение элемента по индексу
public Pair GetItem(int index)
{
if (index >= 0 && index < items.Count)
{
return items[index];
}
throw new IndexOutOfRangeException("Индекс вне диапазона");
}
// Получение количества элементов
public int Count => items.Count;
}
// Демонстрационная программа
class Program
{
static void Main(string[] args)
{
// Создание объектов Money
Money money1 = new Money(100, 50);
Money money2 = new Money(50, 75);
Console.WriteLine("Операции с деньгами:");
Console.Write("money1: ");
money1.Display();
Console.Write("money2: ");
money2.Display();
Money moneySum = (Money)money1.Add(money2);
Console.Write("money1 + money2: ");
moneySum.Display();
try
{
Money moneyDiff = (Money)money1.Subtract(money2);
Console.Write("money1 - money2: ");
moneyDiff.Display();
}
catch (ArgumentException ex)
{
Console.WriteLine($"Ошибка: {ex.Message}");
}
// Создание объектов Complex
Complex complex1 = new Complex(3, 4);
Complex complex2 = new Complex(1, 2);
Console.WriteLine("\nОперации с комплексными числами:");
Console.Write("complex1: ");
complex1.Display();
Console.Write("complex2: ");
complex2.Display();
Complex complexSum = (Complex)complex1.Add(complex2);
Console.Write("complex1 + complex2: ");
complexSum.Display();
Complex complexDiff = (Complex)complex1.Subtract(complex2);
Console.Write("complex1 - complex2: ");
complexDiff.Display();
Complex complexProd = (Complex)complex1.Multiply(complex2);
Console.Write("complex1 * complex2: ");
complexProd.Display();
Complex complexQuot = (Complex)complex1.Divide(complex2);
Console.Write("complex1 / complex2: ");
complexQuot.Display();
// Создание набора и добавление элементов
Series series = new Series();
series.Add(money1);
series.Add(money2);
series.Add(complex1);
series.Add(complex2);
Console.WriteLine("\nОтображение набора:");
series.DisplayAll();
// Выполнение операции с элементами из набора
Console.WriteLine("\nОперация с элементами набора:");
Pair item1 = series.GetItem(0);
Pair item2 = series.GetItem(1);
Console.Write("Элемент 1: ");
item1.Display();
Console.Write("Элемент 2: ");
item2.Display();
Console.Write("Элемент 1 + Элемент 2: ");
Pair result = item1.Add(item2);
result.Display();
}
}
Would you like me to explain or break down the code?