Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

задачи

.docx
Скачиваний:
4
Добавлен:
10.02.2015
Размер:
56.77 Кб
Скачать
  1. Создать класс «измерение», который характеризуется названием измеряемого показателя, значением измерения и названием единицы измерения. Требуется организовать инициализацию данного класса и обеспечить доступ к его элементам.

Создать класс «эксперемент», который содержит массив различных измерений. Требуется обеспечить с помощью методов класса доступ и заполнение результатов эксперемента. Также для этого класса требуется определить методы, которые получают максимальные значения, минимальные и средние значения на базе этого эксперемента для заданных пользователем показателей. Протестировать возможности созданных классов

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

{

class Izmerenie

{

//количество строк и столбцов матрицы(в матрице)

protected int m;

string[] n;

protected double[] zn;

string n2;

public Izmerenie()

{

int m = 2;

string[] n = new string[m];

for (int i = 0; i < m; i++)

n[i] = "ткань";

double[] zn = new double[m];

for (int j = 0; j < m; j++)

zn[j] = 1;

n2 = "м";

}

public Izmerenie(string[] n, double[] zn, string n2)

{

for (int i = 0; i < m; i++)

this.n[i] = n[i];

for (int j = 0; j < m; j++)

this.zn[j] = zn[j];

this.n2 = n2;

}

public void Input()

{

Console.WriteLine("Введите количество измерений");

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

n=new string[m];

Console.WriteLine("Введите названия измеряемых объектов");

for (int i = 0; i < m; i++)

n[i] = Console.ReadLine();

zn = new double[m];

Console.WriteLine("Введите значения измерений для каждого объекта");

for (int j = 0; j < m; j++)

zn[j] = int.Parse(Console.ReadLine());

Console.WriteLine("Введите название ед измерения");

n2 = Console.ReadLine();

}

public void Print()

{

Console.WriteLine("Данные для эксперимента:");

Console.WriteLine("________________________");

for (int i = 0; i < m; i++)

{

Console.Write(n[i] + " ");

}

Console.WriteLine();

for (int j = 0; j < m; j++)

{

Console.Write(zn[j] + n2 + " ");

}

Console.WriteLine();

}

}

class Exsperiment : Izmerenie

{

double max, min, sr;

public Exsperiment()

{

max = 0; min = 0; sr = 0; base.Input();

}

public Exsperiment(double max,double min,double sr, string [] n, double [] zn, string n2):base(n,zn,n2)

{

this.max = max; this.min = min; this.sr = sr;base.Input();

}

public void Max()

{

max = zn[0];

for (int j = 1; j < m; j++)

{

if (zn[j] > max)

max = zn[j];

}

}

public void Min()

{

min = zn[0];

for (int j = 1; j < m; j++)

{

if (zn[j] < min)

min = zn[j];

}

}

public void Sr()

{

double sum = 0;

for (int j = 0; j < m; j++)

{ sum = sum + zn[j]; }

sr = sum / (m-1);

}

public void Print1()

{

//Exsperiment ex = new Exsperiment();

Max();

Min();

Sr();

Console.WriteLine();

Console.WriteLine("Результаты эксперимента:");

Console.WriteLine("________________________");

Console.WriteLine("Max:"+max);

Console.WriteLine("Min:"+min);

Console.WriteLine("Sr:"+sr);

}

}

class Program

{

static void Main(string[] args)

{

//Izmerenie iz = new Izmerenie();

//iz.Input();

//iz.Print();

Exsperiment ex = new Exsperiment();

//ex.Max();

//ex.Min();

//ex.Sr();

ex.Print1();

}

}

}

  1. Вектор с дробями

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace РРрр

{

class Ration

{

int chisl;

int znam;

int znak;

public Ration(int pchisl, int pznam, int pznak)

{

chisl = pchisl;

znam = pznam;

znak = pznak;

}

public Ration r(Ration ob)//один объект

{

Ration res = new Ration(ob.chisl, ob.znam, ob.znak);

res.chisl = chisl * ob.znam - ob.chisl * znam;

res.znam = znam * ob.znam;

return res;

}

public static implicit operator string(Ration ob)

{

string str = " ";

if (ob.znak == -1)

str = "-";

str = str + Convert.ToString(ob.chisl) + "/" + Convert.ToString(ob.znam);

return str;

}

public static Ration Parse(string str)

{

int pchisl;

int pznam;

int pznak;

//str = str.Substring(1, str.Length - 2);

string[] s = str.Split('/');

pchisl = int.Parse(s[0]);

pznam = int.Parse(s[1]);

//pznak = int.Parse(s[0]);

pznak = 1;

if (pchisl < 0)

{

pchisl = -pchisl;

pznak = -1;

}

Ration res = new Ration(pchisl, pznam, pznak);

return res;

}

public Ration у(Ration ob)//один объект

{

Ration res = new Ration(chisl, znam, znak);

res.chisl = chisl * ob.znam - ob.chisl * znam;

res.znam = znam * ob.znam;

return res;

}

public static Ration operator +(Ration ob1, Ration ob2)

{

Ration res = new Ration(ob1.chisl, ob1.znam, ob1.znak);

res.chisl = ob1.chisl * ob2.znam + ob1.znam * ob2.chisl;

res.znam = ob1.znam * ob2.znam;

return res;

}

public static Ration operator -(Ration ob1, Ration ob2)

{

Ration res = new Ration(ob1.chisl, ob1.znam, ob1.znak);

res.chisl = ob1.chisl * ob2.znam - ob2.chisl * ob1.znam;

res.znam = ob1.znam * ob2.znam;

return res;

}

public static Ration operator *(Ration ob1, Ration ob2)

{

Ration res = new Ration(ob1.chisl, ob1.znam, ob1.znak);

res.chisl = ob1.chisl * ob2.chisl;

res.znam = ob1.znam * ob2.znam;

return res;

}

public static Ration operator /(Ration ob1, Ration ob2)

{

Ration res = new Ration(ob1.chisl, ob1.znam, ob1.znak);

res.chisl = ob1.chisl * ob2.znak;

res.znam = ob1.znam * ob2.chisl;

return res;

}

public static Ration operator *(Ration ob1, int t)

{

Ration res = new Ration(ob1.chisl, ob1.znam, ob1.znak);

res.chisl = ob1.chisl * t;

res.znam = ob1.znam ;

return res;

}

public static Ration operator *(int t, Ration ob1)

{

Ration res = new Ration(ob1.chisl, ob1.znam, ob1.znak);

res.chisl = t*ob1.chisl;

res.znam = ob1.znam;

return res;

}

}

class Vector

{

int n;

Ration[] a;

public Vector(int n1)

{

n = n1;

a = new Ration[n];

}

public static Vector Parse(string str)

{

str = str.Substring(1, str.Length - 2);

string[] s = str.Split(',');

Vector res = new Vector(s.Length);

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

res.a[i] = Ration.Parse(s[i]);

return res;

}

public static implicit operator string(Vector v)

{

string str = "(";

for (int i = 0; i < v.n - 1; i++)

str = str + Convert.ToString(v.a[i]) + ",";

str = str + Convert.ToString(v.a[v.n - 1] + ")");

return str;

}

public void Print()

{

Console.WriteLine();

}

public static Vector operator +(Vector ob1, Vector ob2)

{

if (ob1.n != ob2.n)

throw new Exception("Такие вектора складывать нельзя");

Vector res = new Vector(ob1.n);

for (int i = 0; i < ob1.n; i++)

res.a[i] = ob1.a[i] + ob2.a[i];

return res;

}

public static Vector operator -(Vector ob1, Vector ob2)

{

if (ob1.n != ob2.n)

throw new Exception("Такие вектора вычитать нельзя");

Vector res = new Vector(ob1.n);

for (int i = 0; i < ob1.n; i++)

res.a[i] = ob1.a[i] - ob2.a[i];

return res;

}

public static Ration operator *(Vector ob, Vector ob1) //скaлярное произведение

{

if (ob.n != ob1.n)

throw new Exception("Такие вектора умножать нельзя");

Ration res = new Ration(0, 1, 1);

for (int i = 0; i < ob.n; i++)

res = res + ob.a[i] * ob1.a[i];

return res;

}

public static Ration operator /(Vector ob, Vector ob1) //скaлярное произведение

{

if (ob.n != ob1.n)

throw new Exception("Такие вектора умножать нельзя");

Ration res = new Ration(0, 1, 1);

for (int i = 0; i < ob.n; i++)

res = res + ob.a[i] / ob1.a[i];

return res;

}

public static Vector operator *(Vector v, int t) //умножение с числом

{

Vector res = new Vector(v.n);

for (int i = 0; i < v.n; i++)

res.a[i] = v.a[i] * t;

return res;

}

public static Vector operator *(int t, Vector v) //умножение с числом

{

Vector res = new Vector(v.n);

for (int i = 0; i < v.n; i++)

res.a[i] = t * v.a[i] ;

return res;

}

}

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Введите вектор!");

Vector v = Vector.Parse(Console.ReadLine());

Console.WriteLine(" " + v);

Console.WriteLine("Введите ещё один вектор!");

Vector w = Vector.Parse(Console.ReadLine());

Console.WriteLine(" " + w);

try

{

Console.WriteLine("" + v + "+" + w + "=" + (v + w)); //Сумма

}

catch (Exception e) { Console.WriteLine(e.Message); }

try

{

Console.WriteLine("" + v + "-" + w + "=" + (v - w)); //Разница

}

catch (Exception e) { Console.WriteLine(e.Message); }

try

{

Console.WriteLine("" + v + "*" + w + "=" + (v * w)); //Произвед.

}

catch (Exception e) { Console.WriteLine(e.Message); }

try

{

Console.WriteLine("" + v + "/" + w + "=" + (v / w)); //Деление

}

catch (Exception e) { Console.WriteLine(e.Message); }

try

{

Console.WriteLine("" + v + "*" + 2 + "=" + (v *2)); // вектор*2

}

catch (Exception e) { Console.WriteLine(e.Message); }

try

{

Console.WriteLine("" + 5 + "*" + w + "=" + (5* w));//5*вектор

}

catch (Exception e) { Console.WriteLine(e.Message); }

string s = Console.ReadLine();

Ration d = Ration.Parse(s);

}

}

}

  1. Список

using System;

/// <summary>

/// </summary>

class GList

{

int[] array;

/// <summary>

/// Констуктор

/// </summary>

public GList()

{

array = new int[0];

}

/// <summary>

/// Количество элементов в списке

/// </summary>

public int Count

{

get

{

return array.Length;

}

}

/// <summary>

/// Добавление нового элемента в список

/// </summary>

/// <param name="value">Элемент который необходимо вставить</param>

public void Add(int value)

{

int[] buf = new int[array.Length];

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

buf[i] = array[i];

array = new int[buf.Length + 1];

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

array[i] = buf[i];

array[array.Length - 1] = value;

}

/// <summary>

/// Вставляет новый элемент в укзананную позицию.

/// </summary>

/// <param name="value">Новый элемент</param>

/// <param name="pos">Позиция</param>

public void Insert(int value, int pos)

{

if (pos > array.Length || pos < 0)

throw new Exception("Неверная позиция");

int[] buf = new int[array.Length];

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

buf[i] = array[i];

array = new int[buf.Length + 1];

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

array[i] = buf[i];

int buffer = array[pos];

for (int i = array.Length - 2; i >= pos; i--)

{

int d = array[i];

array[i + 1] = d;

}

array[pos] = value;

}

/// <summary>

/// Вывод списка.

/// </summary>

public void Show()

{

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

Console.Write(array[i] + " ");

}

/// <summary>

/// Удаление элемента по указанной позиции

/// </summary>

/// <param name="pos">Позиция. Нумерация начинается с нуля.</param>

public void Remove(int pos)

{

if (pos > array.Length || pos < 0)

throw new Exception("Неверная позиция");

int[] buf = new int[array.Length];

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

buf[i] = array[i];

array = new int[buf.Length - 1];

for (int i = 0; i < pos; i++)

array[i] = buf[i];

for (int i = pos; i < buf.Length - 1; i++)

array[i] = buf[i + 1];

}

/// <summary>

/// Удаляет заданный элемент из списка.

/// </summary>

/// <param name="element">Элемент списка.</param>

public void RemoveElement(int element)

{

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

if (array[i] == element)

Remove(i);

}

/// <summary>

/// Получения массива элементов.

/// </summary>

/// <returns></returns>

public int[] ToArray()

{

return array;

}

/// <summary>

/// Максимальный элемент в списке.

/// </summary>

public int Maximum

{

get

{

int max = array[0];

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

if (array[i] > max)

max = array[i];

return max;

}

}

/// <summary>

/// Максимальный элемент в списке.

/// </summary>

public int Minimum

{

get

{

int min = array[0];

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

if (array[i] < min)

min = array[i];

return min;

}

}

/// <summary>

/// Сумма элементов списка.

/// </summary>

public int Sum

{

get

{

int sum = 0;

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

sum += array[i];

return sum;

}

}

}

class Program

{

static void Main(string[] args)

{

GList l = new GList();

l.Add(1);

l.Add(2);

l.Add(3);

l.Insert(4, 1);

l.Show();

l.Remove(1);

l.RemoveElement(1);

Console.WriteLine();

l.Show();

Console.WriteLine();

Console.WriteLine(l.Sum);

Console.ReadKey(true);

}

}

  1. Вектор

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Вектор

{

class Program

{

class vector

{

int n;

int[] a;

public vector(int n)//конструктор

{

this.n = n;//длина массива

a = new int[this.n];//массив

}

public vector(params int[] a)

{

n = a.Length;//н равно длине массива а

this.a = new int[n];

for (int x = 0; x < n; x++)

{

this.a[x] = a[x];

}

}

public static implicit operator string(vector r)//строковый вывод

{

string s = "";//содаем строку

for (int x = 0; x < r.n - 1; x++)

{

s += (r.a[x] + ",");//координаты

}

s += (r.a[r.n-1] + ",");

return s;

}

public static vector operator +(vector v, vector v2)//перегрузка опреаторв

{

vector res = new vector();

for (int x = 0; x < v.n-1; x++)

{

res.a[x] = v.a[x] + v2.a[x];

}

return res;

}

}

static void Main(string[] args)

{

vector v = new vector(1,2,3,4,5);//создаем вектора

vector v2 = new vector(6, 7, 8, 9, 10);

vector v3 = new vector(5);

v3 = v + v2;//сложение

Console.WriteLine("" + v);//распечатка

Console.WriteLine("" + v3);

}

}

}

  1. Дата

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Дата //учет определенного кл-ва дней в месяце

{

class Date

{

delegate int MethodDelegate();

MethodDelegate chislo = null;

int chislo1()

{

return 30;

}

int chislo2()

{

return 32;

}

int chislo3()

{

return 31;

}

protected int day,mounth,year;

public Date(int x,int y,int z)

{

day=x;

mounth=y;

year=z;

}

public void Print()//распечатываем

{

Console.WriteLine();

if (day < 10)

Console.Write("0" + day+".");

else

Console.Write(day + ".");

if (mounth < 10)

Console.Write("0" + mounth + ".");

else

Console.Write(mounth + ".");

Console.Write(year);

}

public void Razn(Date d1,Date d2)//разность между датой которую ввели и которю потом введем

{

if (d1.year == d2.year)

{

if (d1.mounth == d2.mounth)

Console.WriteLine(Math.Abs(d1.day - d2.day) + "дней");

else

Console.WriteLine(Math.Abs(d1.mounth - d2.mounth) + "месяца(ев) " + Math.Abs(d1.day - d2.day) + " дней");

}

else

{

if (d1.mounth == d2.mounth)

Console.WriteLine(Math.Abs(d1.year-d2.year)+" год(а)(лет) "+Math.Abs(d1.day - d2.day) + " дне й");

else

Console.WriteLine(Math.Abs(d1.year - d2.year) + " (год(а)(лет) " + Math.Abs(d1.mounth - d2.mounth) + " месяца(ев) " + Math.Abs(d1.day - d2.day) + " дней ");

}

}

public void Add(Date d,int k)

{

if (d.mounth == 2 && d.year % 4 == 0)

{

chislo = chislo1;

}

else

{

if (d.mounth < 8 && d.mounth % 2 != 0 || d.mounth > 7 && d.mounth % 2 == 0)

{

chislo = chislo2;

}

if (d.mounth < 7 && d.mounth % 2 == 0 || d.mounth > 7 && d.mounth % 2 != 0)

{

chislo = chislo3;

}

}

while (k!=0)

{

d.day++;

k--;

if (d.day==chislo())

{

d.mounth++;

d.day = 1;

}

}

}

}

class DateTime : Date

{

int hour, minute, second;

public DateTime(int x, int y, int z, int h, int m, int s)

: base(x, y, z)

{

hour = h;

minute = m;

second = s;

}

new public void Print()

{

base.Print();

Console.WriteLine();

if (day < 10)

Console.Write("0" + day + ".");

else

Console.Write(day + ".");

if (mounth < 10)

Console.Write("0" + mounth + ".");

else

Console.Write(mounth + ".");

Console.Write(year);

if (hour < 10)

Console.Write("0" + hour + ":");

else

Console.Write(hour + ":");

if (minute < 10)

Console.Write("0" + minute + ":");

else

Console.Write(minute + ":");

if (second < 10)

Console.Write("0" + second);

else

Console.Write(second);

Console.WriteLine();

}

public void Add(DateTime dt, int k)

{

base.Add(dt,k);

while (k != 0)

{

dt.minute++;

k--;

if (dt.minute == 59)

{

dt.hour++;

}

}

}

}

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Введите дату");

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

Console.WriteLine("Введите месяц");

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

Console.WriteLine("Введите год");

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

Date d = new Date(x, y, z);

d.Print();

Console.WriteLine();

Console.WriteLine("Разность");

Console.WriteLine("Введите дату");

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

Console.WriteLine("Введите месяц");

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

Console.WriteLine("Введите год");

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

Date d2 = new Date(x, y, z);

d2.Print();

Console.WriteLine();

Console.WriteLine("Разность:");

d.Razn(d, d2);

Console.WriteLine("");

Console.WriteLine("Сколько дней вы хотите прибавить к дате?");

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

d.Add(d, k);

d.Print();

Console.WriteLine("Дата-время");

Console.WriteLine("Введите дату");

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

Console.WriteLine("Введите месяц");

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

Console.WriteLine("Введите год");

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

Console.WriteLine("Введите часы");

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

Console.WriteLine("Введите минуты");

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

Console.WriteLine("Введите секунды");

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

DateTime dt = new DateTime(x, y, z, h, m, s);

dt.Print();

Console.WriteLine("");

Console.WriteLine("");

Console.WriteLine("Разность");

Console.WriteLine("Введите дату");

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

Console.WriteLine("Введите месяц");

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

Console.WriteLine("Введите год");

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

Console.WriteLine("Введите часы");

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

Console.WriteLine("Введите минуты");

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

Console.WriteLine("Введите секунды");

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

Console.WriteLine("");

DateTime dt2 = new DateTime(x, y, z, h, m, s);

dt2.Print();

Console.WriteLine("");

Console.WriteLine("Сколько минут вы хотите прибавить к дате?");

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

dt.Add(d, k);

}

}

}

  1. Делегаты

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace Массив__делегаты_

{

class Program

{

class Tovar

{

int number;

string name;

int price;

int kolvo;

public Tovar()

{

number = 0;

name = null;

price = 0;

kolvo = 0;

}

public Tovar(string[]s)

{

number = Convert.ToInt32(s[0]);

name = s[1];

price = Convert.ToInt32(s[2]);

kolvo = Convert.ToInt32(s[3]);

}

public int Number

{

get { return number; }

set { number = value; }

}

public string Name

{

get { return name; }

set { name = value; }

}

public int Price

{

get { return price; }

set { price = value; }

}

public int Kolvo

{

get { return kolvo; }

set { Kolvo = kolvo; }

}

public static bool comparenumber(Tovar t1, Tovar t2)

{

if (t1.Number < t2.Number)

return true;

return false;

}

public static bool compareprice(Tovar t1, Tovar t2)

{

if (t1.Price < t2.Price)

return true;

return false;

}

public static bool comparekolvo(Tovar t1, Tovar t2)

{

if (t1.Kolvo < t2.Kolvo)

return true;

return false;

}

}

class Massiv

{

Tovar [] t = new Tovar[5];

delegate bool MethodDelegate(Tovar t1,Tovar t2);

MethodDelegate method = null;

public Massiv(int i,StreamReader sr)

{

string str = "";

while ((str = sr.ReadLine()) != null)

{

string[] s = str.Split(' ');

Tovar r = new Tovar(s);

for (int j = 0; j < 5; j++)

{

if (t[j] == null)

{

t[j] = r;

break;

}

}

}

Console.WriteLine();

Console.WriteLine("Первоначальный текст:");

Console.WriteLine();

for (int x = 0; x < 5; x++)

{

Console.WriteLine(t[x].Number + " " + t[x].Name + " " + t[x].Price + " " + t[x].Kolvo);

}

if (i != 1 && i != 2 && i != 3)

throw new Exception("Не определены данные для сортировки");

if (i == 1)

method = Tovar.comparenumber;

if (i == 2)

method = Tovar.compareprice;

if (i == 3)

method = Tovar.comparekolvo;

}

public void Sort()

{

for (int x = 0; x < 4; x++)

{

for (int j = x+1; j < 5; j++)

{

if (method(t[x],t[j])==false)

{

Tovar z = t[x];

t[x] = t[j];

t[j] = z;

}

}

}

Console.WriteLine();

Console.WriteLine("Отсортированный текст:");

Console.WriteLine();

for (int x = 0; x < 5; x++)

{

Console.WriteLine(t[x].Number+" "+t[x].Name+" "+t[x].Price+" "+t[x].Kolvo);

}

}

}

static void Main(string[] args)

{

try

{

Console.WriteLine("1 - Сортировка по номеру, 2 - Сортировка по цене, 3-Сортировка по количеству");

StreamReader sr = new StreamReader("D://Делегаты.txt", Encoding.Default);

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

Massiv m = new Massiv(i,sr);

m.Sort();

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

}

}

}

  1. Делегаты функции

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication13

{

delegate double PointIn(Function f, double a, double b);

delegate double Function(double x);

class Solve

{

static PointIn method;

static Solve()

{

int e;

while (e >= 3 || e < 0);

{

Console.WriteLine("Введите 0 для метода деления отрезка");

Console.WriteLine("Введите 1 для метода хорд");

Console.WriteLine("Введите 2 для метода касательных");

// инициализация генератора случайных чисел

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

// Random r = new Random();

//int e = r.Next(300) % 3;

}

switch (e)

{

case 0:

// инициализация делегата функцией GetX1

method = GetX1;

Console.WriteLine("Выбран метод деления отрезка пополам");

break;

case 1:

// инициализация делегата функцией GetX2

method = GetX2;

Console.WriteLine("Выбран метод хорд");

break;

case 2:

// инициализация делегата функцией GetX3

method = GetX3;

Console.WriteLine("Выбран метод касательных");

break;

}

}

// получение середины отрезка

static double GetX1(Function f, double a, double b)

{

return (a + b) / 2;

}

// получение точки пересечения хорды с осью OX

static double GetX2(Function f, double a, double b)

{

return a - f(a) * (b - a) / (f(b) - f(a));

}

// получение точки пересечения касательной с осью OX

static double GetX3(Function f, double a, double b)

{

// приближенное вычисление производной в точке a

double fa = (f(a + 0.001) - f(a)) / 0.001;

if (fa != 0)

{

double c = a - f(a) / fa;// получение точки пересечения касательной с осью абсцисс

if (a <= c && c <= b)// если точка c принадлежит отрезку,выбираем ее

return c;

}

double fb = (f(b + 0.001) - f(b)) / 0.001; // приближенное вычисление производной в точке b

if (fb != 0)

{

double c = b - f(b) / fb; // получение точки пересечения касательной с осью абсцисс

if (a <= c && c <= b)

return c;

}

throw new Exception("Возможно, на этом отрезке корней нет");

}

static public double RootEquation(Function f, double a, double b, double eps)

{

// корень будет существовать, если на концах отрезка у функции знаки различны

if (f(a) * f(b) > 0)

throw new Exception("Возможно, на этом отрезке корней нет"); // продолжаем, пока на одном из концов отрезка не будет получено значение функции с заданной точностью

while (Math.Abs(f(a)) > eps && Math.Abs(f(b)) > eps)

{

// поиск точки деления отрезка - вызов делегата

double c = method(f, a, b);

if (f(c) == 0)// если найденная точка - корень, это решение

return c;

// выбор следующего отрезка

if (f(a) * f(c) < 0)

b = c;

else

a = c;

}

// выбор приближенного значения корня

if (Math.Abs(f(a)) <= eps)

return a;

else

return b;

}

}

class Program

{

static double func(double x)

{

return x * x * x - 6 * x * x + 3 * x + 11;

}

static void Main(string[] args)

{

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

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

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

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

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

double eps = 0.00001;

try

{

Console.WriteLine("Корень = {0}",Solve.RootEquation(func, a, b, eps));

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

}

}

}

  1. Инкапсуляция

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Инкапсуляция//закрытые данные(закрытие переменно)чтобы закрыть не пишем public

{

class Program

{

class Drob

{

int chisl;

int znam;

public Drob()

{

chisl = 0;//данные значения задаются если пустая дробь

znam = 1;

}

public Drob(int ch, int zn)

{

chisl = ch; znam = zn;

}

public Drob Summa(Drob ob)

{

Drob res = new Drob();

res.chisl = chisl * ob.znam + ob.chisl * znam;

res.znam = znam * ob.znam;

return res;

}

public Drob Razn(Drob ob)

{

Drob res = new Drob();

res.chisl = chisl * ob.znam - ob.chisl * znam;

res.znam = znam * ob.znam;

return res;

}

public Drob Proizv(Drob ob)

{

Drob res = new Drob();

res.chisl = chisl * ob.chisl;

res.znam = znam * ob.znam;

return res;

}

public Drob Del(Drob ob)

{

Drob res = new Drob();

res.chisl = chisl * ob.znam;

res.znam = znam * ob.chisl;

return res;

}

public void Print()

{

Console.WriteLine(chisl+","+znam);

}

public static Drob operator +(Drob ob1, Drob ob2)//перегруженный оператор

{

Drob res = new Drob();

res.chisl = ob1.chisl * ob2.znam + ob1.znam * ob2.chisl;

res.znam = ob1.znam * ob2.znam;

return res;

}

public static Drob operator -(Drob ob1, Drob ob2)

{

Drob res = new Drob();

res.chisl = ob1.chisl * ob2.znam - ob1.znam * ob2.chisl;

res.znam = ob1.znam * ob2.znam;

return res;

}

public static Drob operator *(Drob ob1, Drob ob2)

{

Drob res = new Drob();

res.chisl = ob1.chisl * ob2.chisl;

res.znam = ob1.znam * ob2.znam;

return res;

}

public static Drob operator /(Drob ob1, Drob ob2)

{

Drob res = new Drob();

res.chisl = ob1.chisl * ob2.znam;

res.znam = ob1.znam * ob2.chisl;