Помощь в написании студенческих работ
Антистрессовый сервис

Алгоритмы решения задач

РефератПомощь в написанииУзнать стоимостьмоей работы

Дан массив целых чисел A, n>1000. В отсортированном (по неубыванию) методом Шелла массиве найти элемент x (поиск осуществить двумя методами, сравнив их эффективность). Элемент x вводится с клавиатуры, если искомого элемента нет — вывести сообщение. Задание 5. компьютер программирование интерфейс табличный Сумма двух первых цифр заданного четырехзначного числа равна сумме двух его последних цифр… Читать ещё >

Алгоритмы решения задач (реферат, курсовая, диплом, контрольная)

Задание 1.

Разработайте индивидуальный интерфейс (диалоговое окно) по заполнению табличной базы данных и внесите 10 записей. Разработайте и примените диалоговое окно «Выборка» для подсчета выбранных записей из списка на основе самостоятельно заданного критерия.

Листинг программы:

Public Function yy (x As Double) As Double.

yy = Sin (Application.WorksheetFunction.Pi () * x) * Exp (-2 * x).

End Function.

Public Function Komiss (Prodag As Double) As Double.

Const one = 0.08.

Const two = 0.105.

Const three = 0.12.

Select Case Prodag.

Case 0 To 9999.99: Komiss = Prodag * one.

Case 10 000 To 19 999.99: Komiss = Prodag * two.

Case Is >= 20 000: Komiss = Prodag * three.

End Select.

End Function.

Sub Кнопка4_Щелчок ()

UserForm1.Show

End Sub

Sub Кнопка6_Щелчок ()

UserForm2.Show

End Sub

2.

Дан массив целых чисел A[n], n>1000. В отсортированном (по неубыванию) методом Шелла массиве найти элемент x (поиск осуществить двумя методами, сравнив их эффективность). Элемент x вводится с клавиатуры, если искомого элемента нет — вывести сообщение.

Листинг программы:

unit Unit1;

interface.

uses.

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,.

Dialogs, StdCtrls;

type.

TForm1 = class (TForm).

Button1: TButton;

Edit1: TEdit;

ListBox1: TListBox;

Label1: TLabel;

Button2: TButton;

Label2: TLabel;

procedure Button1Click (Sender: TObject);

procedure Button2Click (Sender: TObject);

private.

{ Private declarations }.

public.

{ Public declarations }.

end;

var.

Form1: TForm1;

implementation.

{$R *.dfm}.

procedure TForm1. Button1Click (Sender: TObject);

var A: Array[0.1000] of Integer;

i, w: Integer;

prov:boolean;

begin.

if Edit1. Text=''.

then.

ShowMessage ('Заполните поле!').

else.

try.

prov:=false;

Randomize;

for i := Low (A) to High (A) do.

begin.

A[i] := Random (1000);

ListBox1.Items.Add (IntToStr (A[i]));

end;

w:=strtoint (Edit1.text);

for i:=1 to 1000 do.

if a[i]=w then.

begin.

prov:=true;

label1.caption:='Элемент найден!'.

end;

if not (prov) then.

label1.caption:='Элемент не найден!'.

except.

end;

end;

procedure TForm1. Button2Click (Sender: TObject);

begin.

Listbox1.Clear;

label1.Caption:='';

end;

end.

Задание 3.

Найти максимальный и минимальный элементы и поменять их местами.

Листинг программы:

unit Unit1;

interface.

uses.

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,.

Dialogs, StdCtrls;

type.

TForm1 = class (TForm).

ListBox1: TListBox;

Button1: TButton;

Button2: TButton;

Label1: TLabel;

Label2: TLabel;

procedure Button1Click (Sender: TObject);

procedure Button2Click (Sender: TObject);

private.

{ Private declarations }.

public.

{ Public declarations }.

end;

var.

Form1: TForm1;

a: array [1.25] of integer;

implementation.

{$R *.dfm}.

function MinI: integer;//ищем минимальный.

var.

i: integer;

begin.

result:=a[1];

for i:=1 to 25 do.

if a[result]>a[i] then.

result:=i;

end;

function MaxI: integer;//ищем максимальный.

var.

i: integer;

begin.

result:=a[1];

for i:=1 to 25 do.

if a[result]

result:=i;

end;

procedure Vipolnit;//заполняем массивы.

var.

Ia, m: integer;

begin.

randomize;

Form1.ListBox1.clear;

for Ia:=1 to 25 do begin.

a[Ia]: =random (100);

Form1.ListBox1.items.add (inttostr (a[Ia]));

end;

end;

procedure Prosmotr;//просмотр

var.

Ia, m: integer;

begin.

m:=a[MaxI];

Ia:=a[MinI];

a[MinI]: =m;

a[MaxI]: =Ia;

showmessage ('a[MinI]='+inttostr (a[MinI])+', a[MaxI]='+inttostr (a[MaxI]));

Form1.ListBox1.clear;

for Ia:=1 to 25 do.

Form1.ListBox1.items.add (inttostr (a[Ia]));

end;

procedure TForm1. Button1Click (Sender: TObject);

begin.

Vipolnit;

end;

procedure TForm1. Button2Click (Sender: TObject);

begin.

Prosmotr;

end;

end.

4.

Кодировщик. Написать программу, перекодирующую строку в кодировке KOI в строку в кодировке Windows-1251 и обратно.

Листинг программы:

using System;

using System.Collections.Generic;

using System. Linq;

using System. Text;

using System.Threading.Tasks;

namespace ConsoleApplication2.

{.

class ConvertExampleClass.

{.

static void Main ().

{.

string unicodeString = «Я ганаруся, что жыву у Беларуси!» ;

Encoding ascii = Encoding. ASCII;

Encoding unicode = Encoding. Unicode;

byte[] unicodeBytes = unicode. GetBytes (unicodeString);

byte[] asciiBytes = Encoding. Convert (unicode, ascii, unicodeBytes);

char[] asciiChars = new char[ascii.GetCharCount (asciiBytes, 0, asciiBytes. Length)];

ascii.GetChars (asciiBytes, 0, asciiBytes. Length, asciiChars, 0);

string asciiString = new string (asciiChars);

// Display the strings created before and after the conversion.

Console.WriteLine («Оригинальная строка: {0}», unicodeString);

Console.WriteLine («Ascii строка: {0}», asciiString);

System.Threading.Thread.Sleep (10 000);

}.

}.

}.

Задание 5. компьютер программирование интерфейс табличный Сумма двух первых цифр заданного четырехзначного числа равна сумме двух его последних цифр.

Листинг программы:

using System;

using System.Collections.Generic;

using System. Linq;

using System. Text;

using System.Threading.Tasks;

namespace ConsoleApplication2.

{.

class Program.

{.

static void Main (string[] args).

{.

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

if (x 9999) Console. WriteLine («Число не четырехзначное»);

else if ((x / 1000) + ((x / 100) % 10) == ((x / 10) % 10) + (x % 10)) Console. WriteLine («Равно»);

else Console. WriteLine («Не равно»);

System.Threading.Thread.Sleep (100 000);

}.

}.

}.

Задание 6.

Разработать БД SQL со следующими сущностями: страна, город, область, край.

Листинг программы:

using System;

using System.Collections.Generic;

using System. ComponentModel;

using System. Data;

using System.Data.OleDb;

using System. Drawing;

using System. Linq;

using System. Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace DB_______________________________________.

{.

public partial class Form1: Form.

{.

public Form1().

{.

InitializeComponent ();

}.

private void Form1_Load (object sender, EventArgs e).

{.

// TODO: данная строка кода позволяет загрузить данные в таблицу «_1DataSet.strana». При необходимости она может быть перемещена или удалена.

this.stranaTableAdapter.Fill (this._1DataSet.strana);

// TODO: данная строка кода позволяет загрузить данные в таблицу «_1DataSet.obl». При необходимости она может быть перемещена или удалена.

this.oblTableAdapter.Fill (this._1DataSet.obl);

// TODO: данная строка кода позволяет загрузить данные в таблицу «_1DataSet.city». При необходимости она может быть перемещена или удалена.

this.cityTableAdapter.Fill (this._1DataSet.city);

_1DataSet d = new _1DataSet ();

for (int i = 0; i < d.Tables.Count; i++).

listBox1.Items.Add (d.Tables[i]. TableName);

}.

private void listBox1_DoubleClick (object sender, EventArgs e).

{.

switch (listBox1.SelectedIndex).

{.

case 0:

bindingNavigator1.BindingSource = cityBindingSource;

dataGridView1.DataSource = cityBindingSource;

break;

case 1:

bindingNavigator1.BindingSource = oblBindingSource;

dataGridView1.DataSource = oblBindingSource;

break;

case 2:

bindingNavigator1.BindingSource = stranaBindingSource;

dataGridView1.DataSource = stranaBindingSource;

break;

}.

}.

Задание 7.

Создать XML справочник компьютеров. Структуру XML-документа продумать самостоятельно. Расширить класс Computer средствами работы с XML-документами. Создать контсруктор на основе XML-тега (конструктор прин7имает объект класса XmlNode). Разработать приложение чтения компьютеров из справочника в коллекцию ArrayList. Добавить возможность записи компьютеров в справочник путем добавления нового тега.

Листинг программы:

using System;

using System.Collections.Generic;

using System. Linq;

using System. Text;

using System.Threading.Tasks;

using System. Xml;

using System. Collections;

namespace xml.

{.

class Program.

{.

static void Main (string[] args).

{.

XmlDocument xml = new XmlDocument ();

xml.Load («…Computers.xml»);

XmlNodeList items = xml. GetElementsByTagName («Item»);

// int m=666;

string g="11″ ;

while (Convert.ToString (g) ≠ «0»).

{.

Console.Clear ();

Console.WriteLine («1) Показать записи.»);

Console.WriteLine («2) Добавить запись.»);

Console.WriteLine («3) Добавить в список ArrayList.»);

Console.WriteLine («0) Выход.»);

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

switch (Convert.ToString (g)).

{.

case «1» :

Console.Clear ();

foreach (XmlNode x in items).

{.

Console.WriteLine («Item {0} = {1}», x. Attributes[0]. Name, x. Attributes[0]. Value);

foreach (XmlNode z in x. ChildNodes).

Console.WriteLine («{0,-10}: {1,-10}», z.Name, z. InnerText);

Console.WriteLine (««);

}.

Console.ReadKey ();

break;

case «2» :

Console.Clear ();

XmlNodeList itemss = xml. GetElementsByTagName («Item»);

XmlElement newItem = xml. CreateElement («Item»);

XmlAttribute at = xml. CreateAttribute («id»);

at.Value = Convert. ToString (itemss.Count + 1);

newItem.SetAttributeNode (at);

XmlElement el;

foreach (XmlNode x in itemss[0]. ChildNodes).

{.

el = xml. CreateElement (x.Name);

Console.Write («{0}: «, x.Name);

string name = Console. ReadLine ();

el.InnerText = name;

newItem.AppendChild (el);

}.

xml.DocumentElement.InsertAfter (newItem, xml.DocumentElement.LastChild);

xml.Save («…Computers.xml»);

break;

case «3» :

ArrayList list = new ArrayList ();

XmlNodeList listN = xml. GetElementsByTagName («Item»);

for (int i = 0; i < listN. Count; i++).

list.Add (listN[i]);

Console.Clear ();

Console.WriteLine («Добавлено!»);

Console.ReadKey ();

break;

}.

}.

}.

}.

}.

Задание 8.

Разработать приложение рисования и управления различными геометрическими фигурами.

Листинг программы:

using System;

using System.Collections.Generic;

using System. ComponentModel;

using System. Data;

using System. Drawing;

using System. Linq;

using System. Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace gdi.

{.

public partial class Form1: Form.

{.

private Circle f1;

private Square f2;

private bool stats;

private float sclare;

private float shagSetki;

private Figure f;

private Pen pen;

private PointF cen;

private Color tekColor;// =Color.Red;

Graphics g;

public Form1().

{.

InitializeComponent ();

stats = true;

sclare = (float)1;

shagSetki = 25;

tekColor = Color. Red;

pen = new Pen (tekColor);

this.toolStripLabel4.Text = «X» + Convert. ToString (this.sclare);

}.

private void toolStripButton1_Click (object sender, EventArgs e).

{.

cen = new PointF ();

cen.X = Convert. ToInt32(toolStripTextBox1.Text);

cen.Y = Convert. ToInt32(toolStripTextBox2.Text);

pen = new Pen (tekColor, 3);

if (tabControl1.SelectedIndex == 0).

{.

g = this. tabPage1.CreateGraphics ();

f = new Circle (cen, Convert. ToInt32(toolStripTextBox3.Text), pen, sclare);

}.

else.

{.

g = this. tabPage2.CreateGraphics ();

f = new Square (cen, Convert. ToInt32(toolStripTextBox3.Text), pen, sclare);

}.

tabControl1.Invalidate ();

}.

private void tabPage1_Paint (object sender, PaintEventArgs e).

{.

if (stats).

{.

Pen ww = new Pen (Color.Blue, 1);

PointF p1 =new Point ();

PointF p2 =new Point ();

p1.X=0;

p2.X=tabPage1.Size.Width;

for (float i = tabPage1.Size.Height / 2; i < tabPage1.Size.Height; i += shagSetki * this. sclare)//y.

{.

p1.Y = p2. Y = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

for (float i = tabPage1.Size.Height / 2; i > 0; i -= shagSetki * this. sclare)//y.

{.

p1.Y = p2. Y = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

p1.Y = 0;

p2.Y = tabPage1.Size.Height;

for (float i = tabPage1.Size.Width / 2; i < tabPage1.Size.Width; i += shagSetki * this. sclare)//y.

{.

p1.X = p2. X = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

for (float i = tabPage1.Size.Width / 2; i > 0; i -= shagSetki * this. sclare)//y.

{.

p1.X = p2. X = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

ww.Width = 2;

p1.X = p2. X = tabPage1.Size.Width/2;

p1.Y=0;

p2.Y=tabPage1.Size.Height;

e.Graphics.DrawLine (ww, p1, p2);

p1.Y = p2. Y = tabPage1.Size.Height / 2;

p1.X = 0;

p2.X = tabPage1.Size.Width;

e.Graphics.DrawLine (ww, p1, p2);

}.

if (f ≠ null) f. Draw (g, this. tabPage1. Size);

}.

private void toolStripButton2_Click (object sender, EventArgs e).

{.

stats = !stats;

tabControl1.Invalidate ();

if (stats) toolStripButton2. CheckState = CheckState. Checked;

else toolStripButton2. CheckState = CheckState. Unchecked;

}.

private void tabPage2_Paint (object sender, PaintEventArgs e).

{.

if (stats).

{.

Pen ww = new Pen (Color.Blue, 1);

PointF p1 = new Point ();

PointF p2 = new Point ();

p1.X = 0;

p2.X = tabPage2.Size.Width;

for (float i = tabPage2.Size.Height / 2; i < tabPage2.Size.Height; i += shagSetki * this. sclare)//y.

{.

p1.Y = p2. Y = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

for (float i = tabPage2.Size.Height / 2; i > 0; i -= shagSetki * this. sclare)//y.

{.

p1.Y = p2. Y = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

p1.Y = 0;

p2.Y = tabPage2.Size.Height;

for (float i = tabPage2.Size.Width / 2; i < tabPage2.Size.Width; i += shagSetki * this. sclare)//y.

{.

p1.X = p2. X = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

for (float i = tabPage2.Size.Width / 2; i > 0; i -= shagSetki * this. sclare)//y.

{.

p1.X = p2. X = i;

e.Graphics.DrawLine (ww, p1, p2);

}.

ww.Width = 2;

p1.X = p2. X = tabPage2.Size.Width / 2;

p1.Y = 0;

p2.Y = tabPage2.Size.Height;

e.Graphics.DrawLine (ww, p1, p2);

p1.Y = p2. Y = tabPage2.Size.Height / 2;

p1.X = 0;

p2.X = tabPage2.Size.Width;

e.Graphics.DrawLine (ww, p1, p2);

}.

if (f ≠ null) f. Draw (g, this. tabPage2. Size);

}.

private void toolStripButton5_Click (object sender, EventArgs e).

{.

if (f ≠ null).

{.

f.Move ((float)Convert.ToDouble (this.toolStripTextBox4.Text), this. sclare, Direction. Down);

f.Draw (g, this. tabPage1. Size);

tabControl1.Invalidate ();

}.

}.

private void toolStripButton6_Click (object sender, EventArgs e).

{.

if (f ≠ null).

{.

f.Move ((float)Convert.ToDouble (this.toolStripTextBox4.Text), this. sclare, Direction. Up);

f.Draw (g, this. tabPage1. Size);

tabControl1.Invalidate ();

}.

}.

private void toolStripButton7_Click (object sender, EventArgs e).

{.

if (f ≠ null).

{.

f.Move ((float)Convert.ToDouble (this.toolStripTextBox4.Text), this. sclare, Direction. Left);

f.Draw (g, this. tabPage1. Size);

tabControl1.Invalidate ();

}.

}.

private void toolStripButton8_Click (object sender, EventArgs e).

{.

if (f ≠ null).

{.

f.Move ((float)Convert.ToDouble (this.toolStripTextBox4.Text), this. sclare, Direction. Right);

f.Draw (g, this. tabPage1. Size);

tabControl1.Invalidate ();

}.

}.

private void exitToolStripMenuItem_Click (object sender, EventArgs e).

{.

Application.Exit ();

}.

private void colorToolStripMenuItem_Click (object sender, EventArgs e).

{.

colorDialog1.ShowDialog ();

tekColor = pen. Color = this. colorDialog1.Color;

tabControl1.Invalidate ();

}.

private void toolStripButton3_Click (object sender, EventArgs e).

{.

this.sclare *= 2;

this.toolStripLabel4.Text = «X» + Convert. ToString (this.sclare);

if (f ≠ null) f. Reduce ();

tabControl1.Invalidate ();

}.

private void toolStripButton4_Click (object sender, EventArgs e).

{.

this.sclare /= 2;

this.toolStripLabel4.Text = «X» + Convert. ToString (this.sclare);

if (f ≠ null) f. Increase ();

tabControl1.Invalidate ();

}.

private void tabPage2_MouseDoubleClick (object sender, MouseEventArgs e).

{.

Point p = new Point (e.X, e. Y);

if (f ≠ null) if (f.CheckHit (p)) MessageBox. Show («Попал!»);

}.

private void tabPage1_MouseDoubleClick (object sender, MouseEventArgs e).

{.

Point p = new Point (e.X, e. Y);

if (f ≠ null) if (f.CheckHit (p)) MessageBox. Show («Попал!»);

}.

private void tabControl1_SelectedIndexChanged (object sender, EventArgs e).

{.

this.sclare = 1;

this.toolStripLabel4.Text = «X» + Convert. ToString (this.sclare);

}.

}.

}.

Показать весь текст
Заполнить форму текущей работой