Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ОП6.docx
Скачиваний:
1
Добавлен:
29.06.2023
Размер:
137.25 Кб
Скачать

3 Ход работы

Задание 1:

Рациональная (несократимая) дробь предсавляется парой целых чисел (a,b), где а – числитель, b - знаменатель. Создать класс Rational для работы с рациональными дробями. Обязательно должны быть реализованы операции: сложения, вычитания, умножения, деления и сравнение дробей, причем результат должен приводить в виде несократимой дроби (т.е. результат нужно сокращать)

Реализация данного алгоритма на языке C# представлена в приложении А.

Задание 2:

Создать класс Goods (товар). В классе должны быть представ- лены поля: наименование товара, дата оформления, цена товара, количество единиц товара, номер накладной, по которой товар поступил на склад. Реализовать методы изменения цены товара, изменения количества товара (увеличения и уменьшения), вычисления стоимости товара. Должен быть метод для отображения стоимости товара в виде строки.

Реализация данного алгоритма на языке C# представлена в приложении Б.

Задание 3:

Описать классы ФИГУРА, 4х угольник, треугольник, квадрат, равнобедренный треугольник. Выстроить правильную иерархическую наследования этих классов, определить какие из классов должны быть абстрактными, какие методы абстрактными или виртуальными. Описать конструкторы и деструкторы разработанных классов. Создать по одному объекту каждого класса, для которого это возможно, поместить их в один массив. Для каждого объекта вызвать метод AREA и вывести на экран все свойства каждого из объектов.

UML диаграмма классов для данного алгоритма представлена на рисунке 3.9.

Рисунок 3.9 – UML диаграмма классов

Реализация данного алгоритма на языке C# представлена в приложении В.

4 Заключение

В результате выполнения лабораторной работы были получены навыки использования механизмов инкапсуляции, наследования и полиморфизма. Отчет оформлен согласно ОС ТУСУР.

5 Литература

  1. Харченко С.С. Основы программирования (учебно-методическое пособие). 2020г.

Приложение А

(Обязательное)

using System;

namespace Lab6_1

{

class Rational

{

public int a, b;

public Rational(int A, int B)

{

a = A;

b = B;

}

int[] factorize(int x)

{

int[] factors = new int[1];

factors[0] = 1;

int j = 1;

int div = 2;

while (x > 1)

{

if (x % div == 0)

{

Array.Resize(ref factors, factors.Length + 1);

x = x / div;

factors[j] = div;

j++;

}

div++;

}

return factors;

}

int[] reduction(int[] factA, int[] factB)

{

int[] res = new int[2];

for (int i = 0; i < factA.Length;i++)

{

for (int j = 0; j < factB.Length; j++)

{

if (factA[i] == factB[j])

{

factA[i] = 0;

factB[j] = 0;

}

}

}

int a = 1;

for (int i = 0; i < factA.Length; i++)

{

if (factA[i] != 0)

{

a *= factA[i];

}

}

int b= 1;

for (int i = 0; i < factB.Length; i++)

{

if (factB[i] != 0)

{

a *= factB[i];

}

}

res[0] = a;

res[1] = b;

return res;

}

public void add(int c, int d)

{

Console.WriteLine("Искомая дробь : " + a + "/" + b);

int temp = b;

b = b * d;

c = c * temp;

a = (a * d) + c;

int[] factA = factorize(a);

int[] factB = factorize(b);

int[] ab = reduction(factA, factB);

a = ab[0];

b = ab[1];

Console.WriteLine("Итоговая дробь : " + a + "/" + b);

}

public void subtraction(int c, int d)

{

Console.WriteLine("Искомая дробь : " + a + "/" + b);

int temp = b;

b = b * d;

c = c * temp;

a = (a * d) - c;

int[] factA = factorize(a);

int[] factB = factorize(b);

int[] ab = reduction(factA, factB);

a = ab[0];

b = ab[1];

Console.WriteLine("Итоговая дробь : " + a + "/" + b);

}

public void multiplication(int c, int d)

{

Console.WriteLine("Искомая дробь : " + a + "/" + b);

b = b * d;

a = a * c;

int[] factA = factorize(a);

int[] factB = factorize(b);

int[] ab = reduction(factA, factB);

a = ab[0];

b = ab[1];

Console.WriteLine("Итоговая дробь : " + a + "/" + b);

}

public void division(int c, int d)

{

Console.WriteLine("Искомая дробь : " + a + "/" + b);

int temp = c;

c = d;

d = temp;

b = b * d;

a = a * c;

int[] factA = factorize(a);

int[] factB = factorize(b);

int[] ab = reduction(factA, factB);

a = ab[0];

b = ab[1];

Console.WriteLine("Итоговая дробь : " + a + "/" + b);

}

public void comparison(int c, int d)

{

float A = a / b;

float B = c / d;

if (A > B)

{

Console.WriteLine("Дробь " + a + "/" + b + " > " + c + "/" + d);

}

if (B > A)

{

Console.WriteLine("Дробь " + c + "/" + d + " > " + a + "/" + b);

}

}

}

class Program

{

static void Main(string[] args)

{

Rational rat = new Rational(1,4);

rat.add(1,2);

rat.division(1,2);

rat.multiplication(1,2);

rat.subtraction(1, 2);

rat.comparison(47,1);

}

}

}

Приложение Б

(Обязательное)

using System;

public class Goods

{

public string Name;

public int[] Date = new int[3];

public Double Price;

public int Kol;

public string Number;

public Goods(Double Price, int Kol, string Name, int d, int m, int g, string Number)

{

if (Price >= 0 && Kol >= 0)

{

this.Name = Name;

Date[0] = d;

Date[1] = m;

Date[2] = g;

this.Number = Number;

this.Kol = Kol;

this.Price = Price;

Console.WriteLine("Стоимость товара равна " + this.Price * Kol);

}

else

{

Console.WriteLine("Введено некорректное значение");

}

}

public void MakeP(Double Price)

{

if (Price > 0)

{

this.Price = Price;

Console.WriteLine("Стоимость равна " + this.Price * Kol);

}

else

Console.WriteLine("Некорректный ввод цены");

}

public void MakeK(int Kol)

{

if (Kol > 0)

{

this.Kol = Kol;

Console.WriteLine("Стоимость равна " + Price * Kol);

}

else

Console.WriteLine("Некорректный ввод колличества товара");

}

public string S()

{

return (Convert.ToString(this.Price * Kol));

}

~Goods()

{

}

}

namespace Лабораторная_6_задание_2

{

class Program

{

static void Main(string[] args)

{

Double p;

int k, d, m, g, n,z;

string Na, Nu;

Console.WriteLine("Напиши цену, количество товара, название, день, месяц, год, и номер накладной ");

p = Convert.ToDouble(Console.ReadLine());

k = Convert.ToInt32(Console.ReadLine());

Na = Console.ReadLine();

d = Convert.ToInt32(Console.ReadLine());

m = Convert.ToInt32(Console.ReadLine());

g = Convert.ToInt32(Console.ReadLine());

Nu = Console.ReadLine();

if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) && (d > 31 || d < 1))

Console.WriteLine("Некорректный ввод даты ");

else

if ((m == 4 || m == 6 || m == 9 || m == 11) && (d > 30 || d < 1))

Console.WriteLine("Некорректный ввод даты");

else

if (((g % 4 == 0 && g % 100 != 0) || (g % 100 == 0 && g % 400 == 0)) && (m == 2) && (d > 29 || d < 1))

Console.WriteLine("Некорректный ввод даты");

else

if ((g % 4 != 0 || g % 100 != 0 || g % 400 != 0) && (m == 2) && (d > 28 || d < 1))

Console.WriteLine("Некорректный ввод даты");

else

{

Goods C = new Goods(p, k, Na, d, m, g, Nu);

if (C.Price < 0 || C.Kol < 0)

goto metka;

Console.WriteLine("Если необходимо изменить цену товара введи 1, иначе 0");

n = Convert.ToInt32(Console.ReadLine());

if (n == 1)

{

Console.WriteLine("Введи цену товара ");

z = Convert.ToInt32(Console.ReadLine());

C.MakeP(z);

if (z < 0)

goto metka;

}

Console.WriteLine("Если необходимо изменить количество товара введи 1, иначе 0 ");

n = Convert.ToInt32(Console.ReadLine());

if (n == 1)

{

Console.WriteLine("Введи количество товара ");

z = Convert.ToInt32(Console.ReadLine());

C.MakeK(z);

if (z < 0)

goto metka;

}

Console.WriteLine();

Console.WriteLine(C.S());

metka: { }

}

}

}

}

Приложение В

(Обязательное)

using System;

namespace Lab6_3

{

abstract class figure

{

public virtual void area()

{

}

public virtual void print_properties()

{

}

}

abstract class quadrangle : figure

{

public int a;

}

abstract class triangle : figure

{

public int a, b, c;

}

class square : quadrangle

{

public square()

{

Console.WriteLine("Enter the properties of square");

Console.Write("Enter value of the side ");

a = int.Parse(Console.ReadLine());

}

public override void area()

{

Console.WriteLine("Area of square is " + (a * a));

}

public override void print_properties()

{

Console.WriteLine("The side is " + a);

}

}

class right_triangle : triangle

{

public right_triangle()

{

Console.WriteLine("Enter the properties of right_triangle");

Console.Write("Enter value of the leg #1");

a = int.Parse(Console.ReadLine());

Console.Write("Enter value of the leg #2");

b = int.Parse(Console.ReadLine());

Console.Write("Enter value of the hypotenuse ");

c = int.Parse(Console.ReadLine());

}

public override void area()

{

int s = (a * b) / 2;

Console.WriteLine("Area of friangle is " + s);

}

public override void print_properties()

{

Console.WriteLine("Print the properties of right_triangle");

Console.WriteLine("The leg #1 is " + a);

Console.WriteLine("The leg #2 is " + b);

Console.WriteLine("The hypotenuse is " + c);

}

}

class isosceles_triangle : triangle

{

public isosceles_triangle()

{

Console.WriteLine("Enter the properties of isosceles_triangle");

Console.Write("Enter value of the equal sides ");

a = int.Parse(Console.ReadLine());

Console.Write("Enter value of the third side ");

c = int.Parse(Console.ReadLine());

}

public override void area()

{

int p = (a + a + c) / 2;

int s = (int)Math.Sqrt(p * (p - a) * (p - b) * (p - c));

Console.WriteLine("Area of friangle is " + s);

}

public override void print_properties()

{

Console.WriteLine("Print the properties of isosceles_triangle");

Console.WriteLine("The equal sides is " + a);

Console.WriteLine("The third side is " + c);

}

}

class equilateral_triangle : triangle

{

public equilateral_triangle()

{

Console.WriteLine("Enter the properties of equilateral_triangle");

Console.Write("Enter value of the side ");

a = int.Parse(Console.ReadLine());

}

public override void area()

{

int s = (int)(((a * a) * Math.Sqrt(3)) / 4);

Console.WriteLine("Area of friangle is " + s);

}

public override void print_properties()

{

Console.WriteLine("Print the properties equilateral_triangle");

Console.WriteLine("The side is " + a);

}

}

class Program

{

static void Main(string[] args)

{

square sq = new square();

right_triangle rt = new right_triangle();

isosceles_triangle it = new isosceles_triangle();

equilateral_triangle et = new equilateral_triangle();

Console.WriteLine(" ");

sq.area();

rt.area();

it.area();

et.area();

Console.WriteLine(" ");

sq.print_properties();

rt.print_properties();

it.print_properties();

et.print_properties();

}

}

}

Соседние файлы в предмете Основы программирования