Лабораторные работы С#
- Лабораторная работа №1 (Обработка одномерных массивов)
- Лабораторная работа №2 (Обработка двухмерных массивов)
- Лабораторная работа №3 (Символы и строки)
- Лабораторная работа №4 (Модули и текстовые файлы)
- Лабораторная работа №5 (односвязанный список)
- Лабораторная работа №6 (Windows Form Рекурсивная картинка)
- Лабораторная работа №8 (Закрепление массивов)
- Игра пятнашки (Windows Forms)
- Лабораторная работа по информатике №1 (Тип шифрования – таблицы Виженера)
- Лабораторная работа по информатике №2
(Перевод числа из восьмеричной в десятичную систему счисления)
Лабораторная работа №1 (Windows Forms)
Скачать программу первой лабораторной работы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace C1
{
// Вариант C1
//Из массива удалить четные элементы, стоящие после максимального
class Task
{
public int[] data; //объявление массива для всего класса
public void input() //процедура ввода
{
string tempStr = Console.ReadLine(); //ввод строки
string[] strArrya = tempStr.Split(' ', ',', '.');
int resSize = 0; //объявление переменной и инцилизация ее нулем,
//т. к. в нее будем считать количество годных элементов
for (int i = 0; i < strArrya.Length; i++) // от 0 до длины массива считаем количество
//элементов, которые переводятся в число
{
try
{
int tempValue = Int32.Parse(strArrya[i]);
resSize++;
}
catch { }
}
data = new int[resSize];
resSize = 0;
for (int i = 0; i < strArrya.Length; i++) // от 0 до длины массива заполняем
//новый массив числами
{
try
{
data[resSize] = Int32.Parse(strArrya[i]);
resSize++;
}
catch { }
}
}
public int findMaxPos() //процедура нахождение максимальной позиции
{
int maxPos = 0;
for (int i = 1; i < data.Length; i++)
{
if (data[i] > data[maxPos])
{
maxPos = i;
}
}
return maxPos;
}
public void delByIndex(int index) //процедура удаление элемента из массива по его индексу
{
int[] newArray = new int[data.Length - 1];
for (int i = 0; i < index; i++)
{
newArray[i] = data[i];
}
for (int i = index+1; i < data.Length; i++)
{
newArray[i-1] = data[i];
}
data = newArray;
}
public void process() //процедура обработки массива
{
int maxPos = findMaxPos();
for (int i = maxPos + 1; i < data.Length; i++)
{ //от максимального элемента до длины массива если элемент четный, то удалить
if (data[i] % 2 == 0)
{
delByIndex(i--);
}
}
}
public string output() //процедура записи массива в строку
{
string outStr = "";
for (int i = 0; i < data.Length; i++)
{
outStr += data[i] + " ";
}
return outStr;
}
}
class Program
{
static void Main(string[] args)
{
Task t = new Task();
t.input();//ввод массива
Console.WriteLine();
t.process();//обработка массива
string outStr = t.output();
Console.WriteLine(outStr);//вывод массива
Console.ReadKey();
}
}
}
Наверх ↑
Лабораторная работа №2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _2C11
{
// Вариант C11:
//Ввести двухмерный массив A[N,M] и одномерный массив B[K].
//Удалить из B те элементы, которые являются минимальными элементами столбцов массива A.
class Task
{
public int[,] arrayA; //объявление двухмерного массива A
public int[] arrayB; //объявление одномерного массива B
int n = 5; //количество элементов в столбцах массива A
int m = 10; //количество элементов в строках массива A
int k = 15; //размер массива B
public void input() //процедура ввода
{
arrayA = new int[n, m];
arrayB = new int[k];
Random r = new Random();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arrayA[i, j] = r.Next(0, 20); //заполнение массива A случайными числами
}
}
for (int i = 0; i < arrayB.Length; i++)
{
arrayB[i] = r.Next(0, 20); //заполнение массива B случайными числами
}
}
public void outputArrayA() //процедура вывода массива А
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(arrayA[i, j].ToString().PadLeft(5, ' '));
}
Console.WriteLine();
}
}
public void outputArrayB() //процедура вывода массива В
{
for (int i = 0; i < arrayB.Length; i++)
{
Console.Write(arrayB[i].ToString().PadLeft(5, ' '));
}
}
public void delByIndex(int index) //процедура удаления по индексу элементо из массива В
{
int[] newArray = new int[arrayB.Length - 1];
for (int i = 0; i < index; i++)
{
newArray[i] = arrayB[i];
}
for (int i = index + 1; i < arrayB.Length; i++)
{
newArray[i - 1] = arrayB[i];
}
arrayB = newArray;
}
int[] arrayMin;
public void findMinElements() //процедура нахождения минимальных
//элементов в столбцах массива А
{
arrayMin = new int[m];
for (int i = 0; i < m; i++)
{
int min = 0;
for (int j = 1; j < n; j++)
{
if (arrayA[j, i] < arrayA[min, i])
{
min = j;
}
}
arrayMin[i] = arrayA[min, i];
}
}
public void outputArrayMin() //процедура вывода массива минимальных
//элементов столбцов массива А
{
for (int i = 0; i < arrayMin.Length; i++)
{
Console.Write(arrayMin[i].ToString().PadLeft(5, ' '));
}
Console.WriteLine();
}
public void process() //процедура обработки массива В
{
findMinElements();
for (int i = arrayMin.Length - 1; i > 0; i--)
{
for (int j = arrayB.Length - 1; j > 0; j--)
{
if (arrayB[j] == arrayMin[i])
{
delByIndex(j);
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
Task t = new Task();
t.input(); //ввод А и В
Console.WriteLine("Массив А:");
t.outputArrayA(); //вывод А
Console.WriteLine("Массив В:");
t.outputArrayB(); //вывод В
Console.WriteLine();
t.process(); //Обработка
Console.WriteLine("Массив минимальных элементов столбцов массива А:");
t.outputArrayMin(); //вывод минимальных элементов
Console.WriteLine("Массив В после обработки:");
t.outputArrayB(); //вывод В после обработки
Console.ReadKey();
}
}
}
Наверх ↑
Лабораторная работа №3 (Windows Forms)
Скачать программу третей лабораторной работы
// Вариант C11
//Выделить угловыми скобками слова, в которых нет ни одной буквы,
//содержащейся в последнем слове самой длинной из введенных строк.
//В выделенных словах у всех гласных букв изменить регистр.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _3C11_WindowsForms
{
public partial class Form1 : Form
{
public string[] strArray;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Данная программа выделяет угловыми скобками слова");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
strArray = textBox1.Text.Split("\r\n".ToCharArray());
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Введите текст");
}
process();
textBox2.Text = output();;
}
public int findMaxStringPos()
{
int res = 0;
for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i].Length > strArray[res].Length)
{
res = i;
}
}
return res;
}
public string findLastWord()
{
int res = 0;
int starPos = strArray[findMaxStringPos()].Length - 1;
for (int i = starPos; i > 0; i--)
{
if ("\"\\ .,!&?".Contains(strArray[findMaxStringPos()][starPos]))
{
starPos--;
continue;
}
else
if ("\"\\ .,!&?".Contains(strArray[findMaxStringPos()][i]))
{
break;
}
else
{
res++;
}
}
string lastWord = strArray[findMaxStringPos()].Substring(starPos - res + 1, res);
return lastWord;
}
public bool isBegin(string str, int j)
{
if ("\"\\ .,!&?".Contains(str[j]))
{
return false;
}
else
{
if ((j == 0) && ("\"\\ .,!&?".Contains(str[0]) == false))
{
return true;
}
return ("\"\\ .,!&?".Contains(str[j - 1]));
}
}
public int findWordLength(string str, int posStart)
{
int res = 0;
for (int i = posStart; i < str.Length; i++)
{
if ("\"\\ .,!&?".Contains(str[i]))
{
break;
}
res++;
}
return res;
}
public bool contains(string word)
{
string lastWord = findLastWord();
bool wasChanged = false;
for (int i = 0; i < word.Length; i++)
{
if (lastWord.Contains(word[i]))
{
wasChanged = true;
}
}
return wasChanged;
}
public void toUpper(ref string word)
{
for (int i = 0; i < word.Length; i++)
{
if ("eyuioaуеыаоэяиюё".Contains(word[i]))
{
char tempChar = word[i];
word = word.Remove(i, 1);
word = word.Insert(i, ("" + tempChar).ToUpper());
}
else
if ("EYUOIAУЕЫАОЭЯИЮЁ".Contains(word[i]))
{
char tempChar = word[i];
word = word.Remove(i, 1);
word = word.Insert(i, ("" + tempChar).ToLower());
}
}
}
public void processWord(ref string word)
{
if (word == "")
{
return;
}
if (contains(word) == false)
{
toUpper(ref word);
word = "<" + word + ">";
}
}
public void processString(ref string str)
{
for (int j = 0; j < str.Length; j++)
{
if (isBegin(str, j) == false)
{
continue;
}
else
{
int len = findWordLength(str, j);
string word = str.Substring(j, len);
processWord(ref word);
str = str.Remove(j, len);
str = str.Insert(j, word);
j = j + word.Length;
}
}
}
public void process()
{
for (int i = 0; i < strArray.Length; i++)
{
processString(ref strArray[i]);
}
}
public string output()
{
string outStr = "";
for (int i = 0; i < strArray.Length; i++)
{
outStr = strArray[i] + " ";
}
return outStr;
}
}
}
Наверх ↑
Лабораторная работа №4 (Windows Forms)
Скачать программу четвертой лабораторной работы
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
// №4 Вариант C1
//Выделить угловыми скобками слова, в которых нет ни одной буквы,
//содержащейся в последнем слове самой длинной строки файла.
//В выделенных словах у всех гласных букв изменить регистр.
namespace _4C1WindowsForms {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public string openFileName;
public string saveFileName;
private void button1_Click(object sender, EventArgs e) {
if (saveFileDialog1.ShowDialog() != DialogResult.OK) {
return;
}
saveFileName = saveFileDialog1.FileName;
int tempValue = 0;
progressBar1.Minimum = 0;
progressBar1.Maximum = strArray.Length;
try {
using (StreamWriter writer = new StreamWriter(saveFileName, false,
Encoding.GetEncoding("windows-1251"))) {
using (StreamReader st = new StreamReader(openFileName,
Encoding.GetEncoding("windows-1251"))) {
while (true) {
if (st.Peek() > -1) { //если можно считать
string s = st.ReadLine();
processString(ref s);
tempValue++;
progressBar1.Value = tempValue;
Application.DoEvents();
writer.WriteLine(s);
} else {
break;
}
}
}
}
} catch {
}
}
public static string[] strArray;
public static int findMaxStringPos() // процедура нахождения позиции самой длинной строки
{
int res = 0;
for (int i = 0; i < strArray.Length; i++) {
if (strArray[i].Length > strArray[res].Length) {
res = i;
}
}
return res;
}
public static string sepatator = "\"\\ .,!&?";//
public static string findLastWord() // процедура нахождения последнего слова
{
int maxStringPos = findMaxStringPos();
int res = 0;
int endWord = strArray[maxStringPos].Length - 1;
//конец слова - позиция последнего элемента в самой длинной строке
for (int i = endWord; i >= 0; i--) {
if (sepatator.Contains(strArray[maxStringPos][endWord])) {
//если последняя позиция строки содержит разделители,то конец слова уменьшить на 1
endWord--;
} else {
if (sepatator.Contains(strArray[maxStringPos][i])) { //нахождение длины последнего слова
break;
}
res++;
}
}
string lastWord = strArray[maxStringPos].Substring(endWord - res + 1, res);
return lastWord;
}
public static bool isBegin(string str, int j) //определение начала слова
{
if (sepatator.Contains(str[j])) {
return false;
}
if (j == 0) {
return true;
}
return (sepatator.Contains(str[j - 1]));
}
public static int findWordLength(string str, int posStart) //нахождение длины слова
{
int res = 0;
for (int i = posStart; i < str.Length; i++) {
if (sepatator.Contains(str[i])) {
break;
}
res++;
}
return res;
}
//проверка содержутся ли буквы последнего слова в других словах
public static bool contains(string word)
{
string lastWord = findLastWord();
//bool contains = false;
for (int i = 0; i < word.Length; i++) {
if (lastWord.Contains(word[i])) {
//contains = true;
return true;
}
}
return false;
}
public static void changedRegistor(ref string word) //изменение регистра слова
{
for (int i = 0; i < word.Length; i++)
{
if (("eyuioaуеыаоэяиюё".Contains(word[i])) || ("EYUOIAУЕЫАОЭЯИЮЁ".Contains(word[i])) {
string tempChar = ("eyuioaуеыаоэяиюё".Contains(word[i])) ?
word[i].ToString().ToUpper() : word[i].ToString().ToLower();
word = word.Remove(i, 1);
word = word.Insert(i, tempChar);
}
}
}
public static void processWord(ref string word) //выделение слова квадратными скобками
{
if (word == "") {
return;
}
if (contains(word) == false) {
changedRegistor(ref word);
word = "<" + word + ">";
}
}
public static void processString(ref string str) //обработка строк
{
for (int j = 0; j < str.Length; j++) {
if (isBegin(str, j) == false) {
continue;
}
int len = findWordLength(str, j);
string word = str.Substring(j, len);
processWord(ref word);
str = str.Remove(j, len);
str = str.Insert(j, word);
j = j + word.Length;
}
}
private void button2_Click(object sender, EventArgs e) {
if (openFileDialog1.ShowDialog() != DialogResult.OK) {
return;
}
openFileName = openFileDialog1.FileName;
strArray = File.ReadAllLines(openFileName,
Encoding.GetEncoding("windows-1251"));
}
}
}
Наверх ↑
Лабораторная работа №5 (односвязанный список)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//11. Удалить максимальный из четных элементов.
namespace lab5
{
class ListNode
{
public int data;
public ListNode next;
public ListNode(int _data, ListNode _next)
{
data = _data;
next = _next;
}
}
class MyList
{
public ListNode head = null;
/// <summary>
/// добавление элемента в хвост
/// </summary>
public void PushEnd(int data)
{
if (head == null)
{
head = new ListNode(data, null);
}
else
{
ListNode temp = head;
for (; temp.next != null; temp = temp.next) ;
temp.next = new ListNode(data, null);
}
}
public void delByValue(int data)
{
if (head == null)
{
throw new ApplicationException("пустой список");
}
if (head.data == data)
{
head = head.next;
}
else
{
ListNode temp = head;
for (temp = head; temp.next != null; temp = temp.next)
{
if (temp.next.data == data)
{
temp.next = temp.next.next;
break;
}
}
}
}
/// <summary>
/// проверка на пустоту
/// </summary>
/// <returns></returns>
public bool isEmpty()
{
return (head == null);
}
public string print()
{
string res = "";
for (ListNode temp = head; temp != null; res += temp.data + " ",
temp = temp.next) ;
return (res == "") ? "<пустой список>" : res;
}
/// <summary>
/// взятие из головы
/// </summary>
public int pop()
{
if (isEmpty())
{
throw new ApplicationException("список пуст");
}
ListNode temp = head.next;
int res = head.data;
head = temp;
return res;
}
public int max;
public int findMaxElement(int max)
{
ListNode temp = head;
for (temp = head; temp != null; temp = temp.next)
{
if ((temp.data % 2 == 0) && (temp.data > max))
{
max = temp.data;
}
}
return max;
}
public string proces()
{
if (isEmpty())
{
throw new ApplicationException("список пуст");
}
ListNode temp = head;
bool wasChanged = false;
for (temp = head; temp != null; temp = temp.next)
{//нахождение четного элемента
if (temp.data % 2 == 0)
{
max = temp.data;
wasChanged = true;
}
}
if (wasChanged == false)
{
return "Четных элементов нет!";
}
max = findMaxElement(max);
return max.ToString();
}
public void delElement()
{
max = findMaxElement(max);
delByValue(max);
}
/// <summary>
/// очистка списка
/// </summary>
public void Clear()
{
while (head != null)
{
pop();
}
}
}
class Program
{
static void Main(string[] args)
{
MyList temp = new MyList();
Console.WriteLine("Введите кол-во элементов, которые необходимо занести в список");
int size;
while (!int.TryParse(Console.ReadLine(), out size))
{
Console.WriteLine("Ошибка ввода!");
}
for (int i = 0; i < size; i++)
{
int res;
while (!int.TryParse(Console.ReadLine(), out res))
{
Console.WriteLine("Ошибка ввода!");
}
temp.PushEnd(res);
}
try
{
Console.WriteLine("Максимальный четный элемент : " + temp.proces());
}
catch (ApplicationException s)
{
Console.WriteLine(s.Message);
}
Console.WriteLine("Введённый список:\n" + temp.print());
temp.proces();
temp.delElement();
Console.WriteLine("Обработанный список:\n" + temp.print());
temp.Clear();
Console.ReadKey();
}
}
}
Наверх ↑
Лабораторная работа №6 (Windows Forms Рекурсивная картинка)
Скачать программу шестой лабораторной работы
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Lab6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TranslateTransform(Width / 2, Height / 2);
DrawPolygons1(e.Graphics, 0, new Point(-200, -200), new Point(-200, 200),
new Point(200, 200), new Point(200, -200));
}
private void DrawPolygons1(Graphics e, int level, Point p1, Point p2, Point p3, Point p4)
{
e.DrawLine(Pens.Black, p1, p2);
e.DrawLine(Pens.Black, p2, p3);
e.DrawLine(Pens.Black, p3, p4);
e.DrawLine(Pens.Black, p4, p1);
if (level < 20)
{
DrawPolygons1(e, level + 1, new Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2),
new Point((p2.X + p3.X) / 2, (p2.Y + p3.Y) / 2),new Point((p3.X + p4.X) / 2,
(p3.Y + p4.Y) / 2),new Point((p4.X + p1.X) / 2, (p4.Y + p1.Y) / 2));
}
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
Invalidate();
}
}
}
Наверх ↑
Лабораторная работа №8 (Закрепление массивов)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//11. Ввести массивы А и В. В массив С скопировать те элементы,
//которые есть и в массиве А и в массиве В. Массивы А, В и С отсортировать по
//возрастанию используя сортировку Шелла.
namespace lab8
{
class Task
{
public int[] arrayA;
public int[] arrayB;
public int[] arrayC;
/// <summary>
/// Ввод массивов А и В
/// </summary>
public void input()
{
Console.WriteLine("Введи массив A:");
string tempStrA = Console.ReadLine();
stringToIntArray(tempStrA, out arrayA);
Console.WriteLine("Введи массив B:");
string tempStrB = Console.ReadLine();
stringToIntArray(tempStrB, out arrayB);
}
/// <summary>
/// преобразование строки в массив цисел
/// </summary>
/// <param name="tempStr"></param>
/// <param name="array"></param>
/// <returns></returns>
public void stringToIntArray(string tempStr, out int[] array)
{
string[] strArray = tempStr.Split(' ', ',', '.', '?', '!');
int resSize = 0;
for (int i = 0; i < strArray.Length; i++)
{
try
{
int value = Int32.Parse(strArray[i]);
resSize++;
}
catch { }
}
array = new int[resSize];
resSize = 0;
for (int i = 0; i < strArray.Length; i++)
{
try
{
array[resSize] = Int32.Parse(strArray[i]);
resSize++;
}
catch { }
}
}
/// <summary>
/// Получение массива С
/// </summary>
public void getArrayC()
{
int resSize = 0;
for (int i = 0, j = 0; i < arrayA.Length && j < arrayB.Length; )
{
if (arrayA[i] == arrayB[j])
{
i++;
j++;
resSize++;
}
else if (arrayA[i] < arrayB[j])
{
i++;
}
else
{
j++;
}
}
arrayC = new int[resSize];
int k = 0;
for (int i = 0, j = 0; i < arrayA.Length && j < arrayB.Length;)
{
if (arrayA[i] == arrayB[j])
{
arrayC[k++] = arrayA[i];
i++;
j++;
}
else if (arrayA[i] < arrayB[j])
{
i++;
}
else
{
j++;
}
}
//int resSize = 0;
//for (int i = 0; i < arrayA.Length; i++)
//{
// for (int j = 0; j < arrayB.Length; j++)
// {
// if (arrayA[i] == arrayB[j])
// {
// resSize++;
// }
// }
//}
//arrayC = new int[resSize];
//resSize = 0;
//for (int i = 0; i < arrayA.Length; i++)
//{
// for (int j = 0; j < arrayB.Length; j++)
// {
// if (arrayA[i] == arrayB[j])
// {
// arrayC[resSize] = arrayA[i];
// resSize++;
// }
// }
//}
}
/// <summary>
/// Сортировка методом Шелла
/// </summary>
/// <param name="array"></param>
public void shellSort(ref int[] array)
{
int j;
int step = array.Length / 2;
while (step > 0)
{
for (int i = 0; i < (array.Length - step); i++)
{
j = i;
while ((j >= 0) && (array[j] > array[j + step]))
{
int temp = array[j];
array[j] = array[j + step];
array[j + step] = temp;
j--;
}
}
step /= 2;
}
}
/// <summary>
/// Обработка массивов
/// </summary>
public void process()
{
shellSort(ref arrayA);
shellSort(ref arrayB);
getArrayC();
//shellSort(ref arrayC);
}
/// <summary>
/// Вывод массивов А, В, С
/// </summary>
public void output()
{
Console.Write("A: ");
for (int i = 0; i < arrayA.Length; Console.Write(arrayA[i++] + " ")) ;
Console.WriteLine();
Console.Write("B: ");
for (int i = 0; i < arrayB.Length; Console.Write(arrayB[i++] + " ")) ;
Console.WriteLine();
Console.Write("C: ");
for (int i = 0; i < arrayC.Length; Console.Write(arrayC[i++] + " ")) ;
}
}
class Program
{
static void Main(string[] args)
{
Task t = new Task();
t.input();
t.process();
t.output();
Console.ReadKey();
}
}
}
Наверх ↑
Лабораторная работа по информатике №1
(Тип шифрования – таблицы Виженера)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Тип шифрования – таблицы Виженера (Вижанера)
namespace Informatika_lab1 {
class Task {
// Реализация алгоритма шифра Виженера
// Функция шифрования сообщения
public string encodeMsg(string text, string rawKey) {
int textLen = text.Length;
string key = keyStretch(rawKey, textLen);
string msg = "";
// Шифруем по ф-ле C = (P + K) mod 26
for (int i = 0; i < textLen; i++) {
int p = getCode(text[i]);
int k = getCode(key[i]);
int c = (p + k) % 26;
msg = msg + getChar(c);
}
return msg;
}
// Обратная функция
public string decodeMsg(string text, string rawKey) {
int textLen = text.Length;
string key = keyStretch(rawKey, textLen);
string msg = "";
// Дешифруем по ф-ле P = (C – K) mod 26
for (int i = 0; i < textLen; i++) {
int c = getCode(text[i]);
int k = getCode(key[i]);
int g = (c - k);
int p;
p = (g < 0) ? (g + 26) : (g % 26);
msg = msg + getChar(p);
}
return msg;
}
// Функция для "растяжения" ключа до длины сообщения
public string keyStretch(string key, int textLen) {
int keyLen = key.Length;
int part = textLen % keyLen;
string map = "";
for (int i = 0; i < textLen / keyLen; i++) {
map = map + key;
}
map = map + key.Substring(0, part);
return map;
}
// Вернуть символ по его коду (0-25)
char getChar(int value) {
return (char)(value + 65);
}
// Вернуть код по символу
int getCode(char value) {
return (int)value - 65;
}
}
class Program {
static void Main(string[] args) {
Task t = new Task();
Console.WriteLine("Введите сообщение для кодирования:");
string msg = Console.ReadLine();
Console.Write("Введите ключ: ");
string key = Console.ReadLine();
string res = t.encodeMsg(msg, key);
Console.WriteLine("Закодированное сообщение:" + res);
Console.WriteLine("Введите сообщение для декодирования:");
msg = Console.ReadLine();
Console.Write("Введите ключ: ");
key = Console.ReadLine();
res = t.decodeMsg(msg, key);
Console.WriteLine("Закодированное сообщение:" + res);
Console.ReadKey();
}
}
}
Наверх ↑
Лабораторная работа по информатике №2
(Перевод числа из восьмеричной в десятичную систему счисления)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Перевод числа из системы счисления, заданной вариантом, в десятичную систему счисления.
//Восьмеричная.
namespace ConsoleApplication4 {
class Process {
public void process() {
double valueDec = 0;
Console.Write("Введи в восмеричной:");
string str = Console.ReadLine();
int valueOct = Int32.Parse(str);
bool c = false;
int a = valueOct;
for (int i = 0; i < str.Length; i++) {
if (valueOct % 10 > 7) {
Console.WriteLine("Введённое число не корректно");
Console.ReadKey();
c = false;
break;
}
a = a / 10;
c = true;
}
if (c) {
for (int i = 0; i < str.Length; i++) {
valueDec += (valueOct % 10) * (Math.Pow(8, (double)i));
valueOct = valueOct / 10;
}
Console.WriteLine("В десятичной: {0}", valueDec);
}
}
class Program {
static void Main(string[] args) {
Process p = new Process();
p.process();
Console.ReadKey();
}
}
}
}
Наверх ↑