Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лабораторные работы ОП.pdf
Скачиваний:
0
Добавлен:
23.02.2026
Размер:
2.24 Mб
Скачать

1.5 Лабораторная работа №5. Структуры

Задание 5: дан список учащихся из 10 записей. Каждая запись имеет поля: фамилия, имя, номер класса, оценки по трем предметам: вывести отдельно «хорошистов» (оценки 4 и 5) для указанного извне класса.

Ниже представлен исходный код данной программы на языке программирования C#.

using System;

struct Student

{

public string LastName; public string FirstName; public int ClassNumber; public int[] Grades;

 

public override string ToString()

 

{

 

return $"{LastName} {FirstName}, Класс: {ClassNumber}, Оценки:

 

 

 

{string.Join(", ", Grades)}";

}

}

 

 

 

 

 

 

 

class Program

 

{

static void Main()

 

 

{

Console.WriteLine("Выберите способ заполнения списка учащихся:");

 

 

 

 

Console.WriteLine("1 - Автоматическая генерация");

 

 

Console.WriteLine("2 - Ручной ввод");

 

 

int choice = 0;

 

 

while (true)

 

 

{

Console.Write("Ваш выбор: ");

 

 

 

|| choice == 2))

 

if (int.TryParse(Console.ReadLine(), out choice) && (choice == 1

 

 

 

 

 

{

break;

 

 

 

}

 

 

 

 

 

 

 

else

 

 

 

{

Console.WriteLine("Ошибка: введите 1 или 2.");

 

 

 

}

 

 

}

 

 

 

 

 

Student[] students; if (choice == 1)

{students = GenerateStudents(10);

}

else

{students = ManualInputStudents();

26

}

Console.WriteLine("\nСписок всех учащихся:"); foreach (var student in students)

{ Console.WriteLine(student);

}

 

int targetClass = 0;

 

while (true)

 

{

 

Console.Write("\nВведите номер класса для поиска хорошистов (1-

11): ");

 

 

 

 

if (int.TryParse(Console.ReadLine(), out targetClass) &&

 

 

 

targetClass >= 1 && targetClass <= 11)

 

 

{

break;

 

 

}

 

 

 

 

}

Console.WriteLine("Ошибка: введите число от 1 до 11.");

 

 

 

 

Student[] goodStudents = GetGoodStudents(students, targetClass);

 

Console.WriteLine($"\nХорошисты класса {targetClass}:");

 

if (goodStudents.Length == 0)

{Console.WriteLine("Нет хорошистов.");

}

else

{foreach (var student in goodStudents) { Console.WriteLine(student);

}} }

static Student[] GenerateStudents(int count)

{

Student[] students = new Student[count];

 

 

Random rand = new Random();

 

 

string[] lastNames = { "Иванов", "Петрова", "Сидоров", "Козлов",

"Смирнова", "Федоров", "Никитина", "Васильев", "Алексеева", "Морозов" };

 

 

string[] firstNames = { "Алексей", "Мария", "Иван", "Дмитрий",

"Ольга", "Сергей", "Анна", "Павел", "Екатерина", "Андрей" };

 

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

 

{

students[i] = new Student

 

 

 

 

{

LastName = lastNames[rand.Next(lastNames.Length)],

 

 

 

 

 

 

FirstName = firstNames[rand.Next(firstNames.Length)],

 

 

 

ClassNumber = rand.Next(9, 12),

rand.Next(3, 6) }

 

Grades = new[] { rand.Next(3, 6), rand.Next(3, 6),

 

 

 

}

};

 

 

 

 

}

return students;

 

 

 

27

static Student[] ManualInputStudents()

{

int count = 0;

 

 

 

 

while (true)

 

 

 

{

Console.Write("Введите количество учащихся: ");

 

 

 

 

if (int.TryParse(Console.ReadLine(), out count) && count > 0)

 

 

{

break;

 

 

 

}

 

 

 

 

 

 

 

}

Console.WriteLine("Ошибка: введите положительное число.");

 

 

 

 

 

 

Student[] students = new Student[count];

 

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

 

{

Console.WriteLine($"\nУчащийся {i + 1}:");

 

 

 

 

Console.Write("Фамилия: ");

 

 

string lastName = Console.ReadLine();

 

 

Console.Write("Имя: ");

 

 

string firstName = Console.ReadLine();

 

 

int classNumber = 0;

 

 

while (true)

 

 

{

Console.Write("Номер класса (9-11): ");

 

 

 

 

 

 

 

if (int.TryParse(Console.ReadLine(), out classNumber)

classNumber >= 9 && classNumber <= 11)

 

 

 

{

break;

 

 

 

}

 

 

 

 

 

 

 

}

Console.WriteLine("Ошибка: введите число от 9 до 11.");

 

 

 

 

 

 

 

int[] grades = new int[3];

 

 

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

 

 

{

while (true)

 

 

 

 

 

 

{

Console.Write($"Оценка по предмету {j + 1} (1-5): ");

 

 

 

 

 

 

 

 

 

if (int.TryParse(Console.ReadLine(), out grades[j])

grades[j] >= 1 && grades[j] <= 5)

 

 

 

 

{

break;

 

 

 

 

}

 

 

 

 

 

 

 

 

}

Console.WriteLine("Ошибка: введите число от 1 до 5.");

 

 

}

 

 

 

 

 

 

 

 

 

students[i] = new Student

{LastName = lastName, FirstName = firstName, ClassNumber = classNumber, Grades = grades

 

}

};

 

 

}

return students;

 

 

28

&&

&&

static Student[] GetGoodStudents(Student[] students, int targetClass)

{

int goodCount = 0;

foreach (var student in students)

{if (student.ClassNumber == targetClass)

{

bool isGood = true;

foreach (var grade in student.Grades)

{if (grade < 4)

{

isGood = false; } break;

}

} }

if (isGood) goodCount++;

Student[] goodStudents = new Student[goodCount]; int index = 0;

 

 

foreach (var student in students)

 

 

{

if (student.ClassNumber == targetClass)

 

 

 

 

 

 

{

bool isGood = true;

 

 

 

 

 

 

 

 

foreach (var grade in student.Grades)

 

 

 

 

{

if (grade < 4)

 

 

 

 

 

 

 

 

 

 

{

isGood = false;

 

 

 

 

 

 

 

 

 

 

 

}

break;

 

 

 

 

}

 

 

 

 

 

 

 

 

 

 

 

if (isGood)

 

 

 

 

{

goodStudents[index] = student;

 

 

 

 

 

 

 

 

 

 

index++;

 

 

 

}

}

 

 

 

 

}

 

 

 

 

 

 

 

 

 

 

}

return goodStudents;

}

 

 

 

 

 

 

 

 

 

 

 

29

Результат работы программы представлен на рисунке 1.33.

Рисунок 1.33 — Результат работы программы задания 5

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

Рисунок 1.34 — Результат работы программы задания 5

30