Files
dz5/main.cpp
2024-11-23 16:48:00 +03:00

219 lines
5.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <iostream>
#include <fstream>
#include <cctype>
#include <limits>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cmath>
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<int>::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<string> binaryArray = { "101", "110", "1111", "10010" };
// Массив для хранения чисел в пятеричной системе
vector<string> 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;
}
int main() {
setlocale(LC_ALL, "");
/*z1launcher();*/
z4_16();
return 0;
}