#include #include #include #include #include #include #include #include #include #include // Для форматирования вывода using namespace std; // Функция перевода из двоичной строки в десятичное число int binaryToDecimal(const string& binary) { int decimal = 0; for (char c : binary) { decimal = decimal * 2 + (c - '0'); } return decimal; } // Функция перевода из десятичного числа в пятеричную систему string decimalToBase5(int decimal) { if (decimal == 0) return "0"; string base5 = ""; while (decimal > 0) { base5 += (decimal % 5) + '0'; decimal /= 5; } reverse(base5.begin(), base5.end()); return base5; } int gcdDivision(int a, int b) { while (b != 0) { int remainder = a % b; a = b; b = remainder; } return a; } int gcdSubtraction(int a, int b) { while (a != b) { if (a > b) a -= b; else b -= a; } return a; } int z1(int a, int b, int method) { switch (method) { case 1: return gcdDivision(a, b); case 2: return gcdSubtraction(a, b); default: cout << "Некорректный выбор метода. Выберите 1 или 2." << endl; return -1; } } void findLeastFrequentVowel(const string& filePath) { ifstream file(filePath); if (!file) { cerr << "Не удалось открыть файл." << endl; return; } int counts[6] = { 0 }; // Счётчики для гласных: a, e, i, o, u, y char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' }; char ch; while (file >> noskipws >> ch) { ch = tolower(ch); for (int i = 0; i < 6; ++i) { if (ch == vowels[i]) { ++counts[i]; break; } } } file.close(); int minCount = numeric_limits::max(); char leastVowel; for (int i = 0; i < 6; ++i) { if (counts[i] > 0 && counts[i] < minCount) { minCount = counts[i]; leastVowel = vowels[i]; } } if (leastVowel) { cout << "Наименее часто встречающаяся гласная: " << leastVowel << " (" << minCount << " раз)" << endl; } else { cout << "В файле нет гласных букв." << endl; } } void z3_22() { string filePath; filePath = "txt.txt"; findLeastFrequentVowel(filePath); } void z1launcher() { int a, b, method; cout << "Введите два положительных целых числа: "; if (!(cin >> a >> b) || a <= 0 || b <= 0) { cout << "Ошибка: ввод должен быть положительными целыми числами." << endl; return; } cout << "Выберите метод:\n1 - Деление\n2 - Вычитание\nВаш выбор: "; if (!(cin >> method) || (method != 1 && method != 2)) { cout << "Ошибка: некорректный выбор метода. Введите 1 или 2." << endl; return; } int result = z1(a, b, method); if (result != -1) { cout << "НОД = " << result << endl; } } void findWordCombination(const string& fileName, const string& combination) { ifstream file(fileName); if (!file.is_open()) { cerr << "Не удалось открыть файл: " << fileName << endl; return; } string line; size_t lineNumber = 0; bool found = false; while (getline(file, line)) { ++lineNumber; // Проверяем, содержит ли строка указанное сочетание слов if (line.find(combination) != string::npos) { found = true; cout << "Найдено в строке " << lineNumber << ": " << line << endl; } } if (!found) { cout << "Сочетание \"" << combination << "\" не найдено в файле." << endl; } file.close(); } void z3_16() { string fileName, combination; fileName = "txt2.txt"; cout << "Введите сочетание слов для поиска: "; cin >> combination; findWordCombination(fileName, combination); } void z4_22() { // Входной массив F[1:n] в двоичной системе vector binaryArray = { "101", "110", "1111", "10010" }; // Массив для хранения чисел в пятеричной системе vector base5Array; // Преобразуем числа for (const string& binary : binaryArray) { int decimal = binaryToDecimal(binary); // Перевод в десятичное string base5 = decimalToBase5(decimal); // Перевод в пятеричное base5Array.push_back(base5); } // Вывод результата cout << "Числа в пятеричной системе: "; for (const string& num : base5Array) { cout << num << " "; } cout << endl; } void z4_16() { double epsilon; // Входное значение ε cout << "Введите значение epsilon: "; cin >> epsilon; double y = 0; // Итоговая сумма int n = 1; // Начальный индекс const double limit = epsilon; // Условие для множителя while (true) { double term = pow(1.0 / 3, n) * pow(cos(pow(3, n - 1)), 3); if (pow(1.0 / 3, n) < limit) { break; // Условие выхода из цикла } y += term; n++; } cout << "Результат вычислений: y = " << y << endl; } string convertToBase(int number, int base) { string result; const char digits[] = "0123456789"; while (number > 0) { result += digits[number % base]; number /= base; } reverse(result.begin(), result.end()); return result.empty() ? "0" : result; // Если число 0, вернуть "0" } void z5_16() { string inputFile = "input.txt"; // Исходный файл string outputFile = "output.txt"; // Файл для результатов ifstream inFile(inputFile); ofstream outFile(outputFile); if (!inFile.is_open()) { cerr << "Не удалось открыть файл " << inputFile << endl; } if (!outFile.is_open()) { cerr << "Не удалось открыть файл " << outputFile << endl; } int base; cout << "Введите целевую систему счисления (от 2 до 9): "; cin >> base; if (base < 2 || base > 9) { cerr << "Система счисления должна быть в пределах от 2 до 9." << endl; } string hexNumber; while (inFile >> hexNumber) { int decimalNumber = stoi(hexNumber, nullptr, 16); // Преобразование из 16-й в 10-ю систему string converted = convertToBase(decimalNumber, base); outFile << converted << endl; } cout << "Перевод завершен. Результаты сохранены в файл " << outputFile << endl; inFile.close(); outFile.close(); } // Структура для хранения данных о стране struct Country { string name; int gold; int silver; int bronze; int totalMedals; int points; // Вычислить общее число медалей и очков void calculate() { totalMedals = gold + silver + bronze; points = gold * 7 + silver * 6 + bronze * 5; } }; bool compareByGold(const Country& a, const Country& b) { if (a.gold != b.gold) { return a.gold > b.gold; // Сортировка по золотым медалям } return a.totalMedals > b.totalMedals; // Вторичная сортировка по общему количеству медалей } void z5_22() { vector countries; int n; cout << "Введите количество стран: "; cin >> n; // Ввод данных for (int i = 0; i < n; ++i) { Country country; cout << "Введите название страны (пожалуйста на Английском): "; cin >> country.name; cout << "Введите количество золотых, серебряных и бронзовых медалей: "; cin >> country.gold >> country.silver >> country.bronze; country.calculate(); countries.push_back(country); } // Сортировка стран sort(countries.begin(), countries.end(), compareByGold); // Сохранение данных в файл ofstream outFile("olympic_results.txt"); if (!outFile) { cerr << "Ошибка открытия файла для записи!" << endl; } outFile << left << setw(15) << "Страна" << setw(10) << "Золото" << setw(10) << "Серебро" << setw(10) << "Бронза" << setw(15) << "Всего Медалей" << setw(10) << "Очки" << endl; for (const auto& country : countries) { outFile << left << setw(15) << country.name << setw(10) << country.gold << setw(10) << country.silver << setw(10) << country.bronze << setw(15) << country.totalMedals << setw(10) << country.points << endl; } outFile.close(); // Вывод данных на экран cout << left << setw(15) << "Страна" << setw(10) << "Золото" << setw(10) << "Серебро" << setw(10) << "Бронза" << setw(15) << "ВсегоМедалей" << setw(10) << "Очки" << endl; for (const auto& country : countries) { cout << left << setw(15) << country.name << setw(10) << country.gold << setw(10) << country.silver << setw(10) << country.bronze << setw(15) << country.totalMedals << setw(10) << country.points << endl; } cout << "Результаты сохранены в файл 'olympic_results.txt'." << endl; } void showMenu() { cout << "Меню задач:\n"; cout << "1. «Алгоритм Евклида»\n"; cout << "3. 3.16\n"; cout << "4. 3.22\n"; cout << "6. 4.16\n"; cout << "7. 4.22\n"; cout << "8. 5.16\n"; cout << "9. 5.22\n"; cout << "0. Выход\n"; } void launchTasks() { int choice; do { showMenu(); cout << "Выберите номер задачи для запуска (или 0 для выхода): "; cin >> choice; switch (choice) { case 1: z1launcher(); break; case 3: z3_16(); break; case 4: z3_22(); break; case 6: z4_16(); break; case 7: z4_22(); break; case 8: z5_16(); break; case 9: z5_22(); break; case 0: cout << "Выход из программы.\n"; break; default: cout << "Ошибка: неверный выбор. Пожалуйста, попробуйте снова.\n"; } cout << endl; } while (choice != 0); } int main() { setlocale(LC_ALL, ""); launchTasks(); return 0; }