Skip to content

Instantly share code, notes, and snippets.

@hellyet
Created December 6, 2022 16:49
Show Gist options
  • Select an option

  • Save hellyet/ad3f29158126e3df139c3e3b217ef3af to your computer and use it in GitHub Desktop.

Select an option

Save hellyet/ad3f29158126e3df139c3e3b217ef3af to your computer and use it in GitHub Desktop.
#include <iostream>
#include <math.h>
#include <string>
#include <iomanip>
#include <vector>
#include <Windows.h>
using namespace std;
const float pi = 3.14159274;
// Здание 1
/*Площадь круга и длина окружности по радиусу*/
pair<float, float> calcCircl(float radius) {
return { (2. * pi * radius), pi * pow(radius, 2) }; // длина площадь
}
/*Площадь треугольника стороны a b c*/
float calcTriangleSquare(float a, float b, float c) {
float p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
/*Высота треугольника стороны a b c*/
float calcTriangleHeight(float a, float b, float c) {
float S = calcTriangleSquare(a, b, c);
return (2 * S/ c);
}
/*Длина окружности описанная около треугольника abc*/
float calcCircleNearTriangle(float a, float b, float c) {
float S = calcTriangleSquare(a, b, c);
float R = (a * b * c) / (4 * S);
auto ps = calcCircl(R); // auto [P, _S] = calcCircl(R) ПОЧЕМУ-ТО ***** НЕ РАБОТАЕТ!!!!!
return ps.first;
}
/*Длина окружности вписанная в треугольник abc*/
float calcLenghtCircleNearTriangle(float a, float b, float c) {
float S = calcTriangleSquare(a, b, c);
float R = (2 * S) / (a + b + c);
auto ps = calcCircl(R);
return ps.first;
}
// Задание 3
double geometricMean(int n) {
/* Составить программу вычисления среднего геометрического N первых натуральных чисел.*/
double gm = 1.0;
int i;
for (i = 1; i <= n; i++)
gm *= i;
return pow(gm, 1./(i-1));
}
int evenSumm(int m, int n) {
/* Составить программу вычисления произведения четных натуральных чисел от M до N.*/
int prod = 1;
for (m; m <= n; m++)
if (m % 2 == 0)
prod *= m;
return prod;
}
float dividerMax(int a, int b) {
/*Составить программу нахождения наибольшего общего делителя 2 чисел.*/
while (a > 0 && b > 0)
if (a > b)
a %= b;
else
b %= a;
return a + b;
}
// Задание 4
void matrix() {
/*
Напишите следующие функции для работы с массивами :
1) Найти сумму элементов одномерного массива;
2) Найти произведение элементов одномерного массива;
3) Найти сумму элементов матрицы, расположенных на главной диагонали;
4) Найти сумму элементов матрицы, расположенных ниже главной диагонали;
5) Найти сумму элементов матрицы, расположенных выше главной диагонали;
6) Найти произведение элементов матрицы, расположенных на побочной диагонали;
7) Найти максимумы четных строк матрицы;
8) Найти минимумы нечетных столбцов матрицы;
9) Найти произведение двух матриц.
*/
const int arr[16] = { 5, 37, 79, 20, 55, 86, 28, 20, 63, 59, 18, 43, 93, 76, 18, 16 };
const int matrix1[5][5] = {
{32, 64, 71, 62, 31},
{7, 46, 16, 14, 38},
{13, 9, 39, 47, 1},
{42, 37, 45, 17, 2},
{30, 17, 4, 18, 48}
};
const int matrix2[5][5] = {
{49, 15, 15, 4, 6},
{26, 20, 20, 31, 42},
{22, 4, 50, 34, 40},
{37, 41, 50, 38, 36},
{12, 38, 4, 49, 49}
};
int arr_summ = 0,
arr_prod = 1,
mat_summ_main = 0,
mat_summ_l_main = 0,
mat_summ_h_main = 0,
mat_summ_sub = 0,
mat_global_prod[5][5] =
{
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
int mat_max[2] = { 0, 0 }; // костыль т.к. <= 0 нету
int mat_min[3] = { 100, 100, 100 }; // костыль т.к. >= 100 нету
// Сумма и произведение элементов массива (1, 2)
for (int i = 0; i < 16; i++) {
arr_summ += arr[i];
arr_prod *= arr[i];
}
// Суммы диагональных элементов матриц (3, 4, 5)
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == j) // на главной диагонали
mat_summ_main += matrix1[i][j];
if (j == i + 1) // выше главной
mat_summ_h_main += matrix1[i][j];
if (i == j + 1) // ниже главной
mat_summ_l_main += matrix1[i][j];
}
}
// Произведение элементов побочной диагонали (6)
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i - j == -4 || i - j == -2 || i - j == 0 || i - j == 2 || i - j == 4) // если на побочной диагонали, формулу вывести не получилось :(
mat_summ_sub += matrix1[i][j];
}
}
int a = 0;
// Максимум чётных строк (7)
for (int i = 0; i < 5; i++) {
if ((i + 1) % 2 == 0) {
for (int j = 0; j < 5; j++) {
if (matrix1[i][j] > mat_max[a])
mat_max[a] = matrix1[i][j];
}
a++;
}
}
a = 0;
// Минимум нечётных строк (8)
for (int i = 0; i < 5; i++) {
if ((i + 1) % 2 != 0) {
for (int j = 0; j < 5; j++) {
if (matrix1[i][j] < mat_min[a])
mat_min[a] = matrix1[i][j];
}
a++;
}
}
// Произведение двух матриц (9)
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
mat_global_prod[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
cout << "\t1) Сумма элементов массива = " << arr_summ << endl;
cout << "\t2) Произведение элементов массива = " << arr_prod << endl;
cout << "\t3) Сумма эл. матрицы главной диагонали = " << mat_summ_main << endl;
cout << "\t4) Сумма эл. матрицы ниже главной диагонали = " << mat_summ_l_main << endl;
cout << "\t5) Сумма эл. матрицы выше главной диагонали = " << mat_summ_h_main << endl;
cout << "\t6) Сумма эл. матрицы побочной диагонали = " << mat_summ_sub << endl;
string c_min = "", c_max = "";
for (int i = 0; i < 2; i++)
c_max += to_string(mat_max[i]) + " ";
for (int i = 0; i < 3; i++)
c_min += to_string(mat_min[i]) + " ";
cout << "\t7) Максимумы чётных строк: " << c_max << endl;
cout << "\t8) Минимумы нечётных строк: " << c_min << endl;
cout << "\t9) Произведение двух матриц" << endl;
for (int i = 0; i < 5; i++) {
cout << "\t ";
for (int j = 0; j < 5; j++) {
cout << setw(6) << mat_global_prod[i][j];
}
cout << endl;
}
cout << endl;
}
// Здание 6
void tableExpression() {
// https://drive.google.com/drive/folders/1tdJb17E9DyNQaj4BW3OfCkDh1TtV08Hq
// Вариант 3
double e = 2.7182818284;
double a, b, itr;
cout << "\tУкажите диапазон через пробел: ";
cin >> a >> b;
cout << "\tУкажите интервал : ";
cin >> itr;
vector<double> f;
vector<double> x;
for (double i = a; i <= b; i+=itr) {
x.push_back(i);
f.push_back(log(1 + sinh(i) + pow(e, -i) - 1) / pow(i, 3));
}
// Вывод
cout << setw(6) << "x";
cout << setw(6) << "f(x)" << endl;
for (int i = 0; i < f.size(); i++) {
cout << setw(6) << x[i] << " ";
cout << setw(8) << f[i] << endl;
}
cout << endl;
}
struct Employer
{
int number;
string ln, fn, pn;
float salary;
string pos;
char sex;
};
// Задание 7
void structures() {
/*
В программе определить массив структур. Каждая структура хранит информацию о работнике фирмы: табельный номер, ФИО, оклад, должность, пол.
Заполнить массив с клавиатуры. Затем программа должна уметь ответить на следующие вопросы:
1) посчитать фонд зарплаты фирмы;
2) посчитать количество женщин и количество мужчин, работающих в фирме;
3) посчитать фонд зарплаты отдельно для мужчин и отдельно для женщин.
*/
cout << "\tКол-во сотрудников: ";
int emp_count;
cin >> emp_count;
Employer* Employers = new Employer[emp_count];
for (int i = 0; i < emp_count; i++) {
cout << "\tРаботник " << i+1 << endl << '\t';
for (int _c = 0; _c <= 18; _c++) cout << '_';
cout << endl;
cout << "\tТабельный номер: ";
cin >> Employers[i].number;
cout << "\tФамидия: ";
cin >> Employers[i].fn;
cout << "\tИмя: ";
cin >> Employers[i].ln;
cout << "\tОтчество: ";
cin >> Employers[i].pn;
cout << "\tОклад: ";
cin >> Employers[i].salary;
cout << "\tДолжность: ";
cin >> Employers[i].pos;
cout << "\tПол (М/Ж): ";
cin >> Employers[i].sex;
cout << endl;
}
float fond = 0;
int count_m = 0, count_f = 0;
float fond_m = 0, fond_f = 0;
for (int i = 0; i < emp_count; i++) {
fond += Employers[i].salary;
Employers[i].sex == 'М' ? count_m++, fond_m += Employers[i].salary : count_f++, fond_f += Employers[i].salary;
}
cout << "\tФон зарплаты фирмы: " << fond << "" << endl;
cout << "\t\tЖенщины: " << fond_f << " | Мужчины: " << fond_m << endl;
cout << "\tЖенщины: " << count_f << " | Мужчины: " << count_m << endl;
}
// Задание 8
void leksems() {
/*
Написать программу для распознавания лексем.
Задача - преобразовать последовательность символов, вводимых с клавиатуры в последовательность лексем языка программирования. В языке имеется следующие лексемы:
1) Идентификатор – последовательность букв и цифр, начинающаяся с буквы;
2) Число – последовательность цифр;
3) Лексемы больше-равно, меньше-равно, присвоить ( >=, <=, := ).
Результатом работы программы является массив структур, где каждая структура хранит саму лексему, а также ее название.
Выдать его содержимое на экран. Обрабатывать ошибки в случае неправильного ввода.
*/
}
int main()
{
// setlocale(LC_ALL, "Russian");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
// Задание 1
const float z1r = 3.3; // радиус окружности
const float z1a = 6.3, z1b = 8.4, z1c = 4.7; // стороны треугольника
auto z1 = calcCircl(z1r);
float z2 = calcTriangleHeight(z1a, z1b, z1c);
float z3 = calcTriangleSquare(z1a, z1b, z1c);
float z4 = calcCircleNearTriangle(z1a, z1b, z1c);
float z5 = calcLenghtCircleNearTriangle(z1a, z1b, z1c);
cout << "Задание 1" << endl;
cout << "\tПлощадь круга = " + to_string(z1.second) + " | Длина окружности = " + to_string(z1.first) << endl;
cout << "\tВысота треугольника = " + to_string(z2) << endl;
cout << "\tПлощадь треугольника = " + to_string(z3) << endl;
cout << "\tДлина описанной окружности = " + to_string(z4) << endl;
cout << "\tДлина вписанной окружности = " + to_string(z5) << endl;
for (int _c = 0; _c <= 48; _c++) cout << " -";
cout << endl;
// Задание 3
int z3_n = 6;
int z3m = 4, z3n = 12;
int z3a = 45, z3b = 63;
cout << "Задание 3" << endl;
cout << "\tСр. геометрическое " << z3_n << " первых натуральных чисел = " << geometricMean(z3_n) << endl;
cout << "\tПроизведение чётных натуральных чисел от " << z3m << " до " << z3n << " = " << evenSumm(z3m, z3n) << endl;
cout << "\tНаибольший Общий Делитель " << z3a << " и " << z3b << " = " << dividerMax(z3a, z3b) << endl;
for (int _c = 0; _c <= 48; _c++) cout << " -";
cout << endl;
cout << "Задание 4" << endl;
matrix();
for (int _c = 0; _c <= 48; _c++) cout << " -";
cout << endl << endl;
cout << "Задание 6" << endl;
tableExpression();
for (int _c = 0; _c <= 48; _c++) cout << " -";
cout << endl << endl;
cout << "Задание 7" << endl;
structures();
for (int _c = 0; _c <= 48; _c++) cout << " -";
cout << endl << endl;
/*cout << "Задание 8" << endl;
for (int _c = 0; _c <= 48; _c++) cout << " -";
cout << endl << endl; */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment