-
Notifications
You must be signed in to change notification settings - Fork 33
Гущин Андрей #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Гущин Андрей #25
Changes from all commits
28d08cd
74d74df
69700c1
c4df47e
b83a96f
9ac64e2
62eec26
934f30d
7b75756
8b8b294
ef05ef7
ac1a145
3c0000c
d49f95d
9eb26d0
7977551
a328691
25e327f
0ed0241
23c09fd
dc7e2ca
31c0c0e
aba1f07
fa0ab69
1ddb73c
31865a2
376dc49
92a4646
c4492a4
e85e397
7791b0b
5904d15
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,10 @@ | ||
| #include <cstdint> | ||
| #include <stdexcept> | ||
|
|
||
| #include <cstddef> // заголовочный файл с целочисленными типами фиксированного размера | ||
| #include <stdexcept> // из этого мы ничего не используем | ||
|
|
||
| // функция принимает две перменных типа int и возвращает число типа int64_t | ||
| int64_t Addition(int a, int b) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } | ||
|
|
||
| // Чтобы сложение выполнялось в int64_t, приводим a и b к этому типу | ||
| // static_cast<новый тип>(переменная) | ||
| return static_cast<int64_t>(a) + static_cast<int64_t>(b); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,88 @@ | ||
| #include <cstddef> | ||
| #include <stdexcept> | ||
|
|
||
| #include <cctype> // применял isspace, isdigit, isupper, islower, toupper | ||
|
|
||
| size_t CharChanger(char array[], size_t size, char delimiter = ' ') { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| if (size == 0) { | ||
| return 0; | ||
| } | ||
|
|
||
| size_t read = 0; // это индекс для чтения | ||
| size_t write = 0; // это индекс для запси символов | ||
|
|
||
| // идем по массиву пока не выйдем за него | ||
| // и пока текущий символ не конец строки, конец строки по условию это '\0' | ||
| while (read < size && array[read] != '\0') { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. много лишних комментариев, невозможно читать код |
||
| // в cppreference указано, что isspace должно принимать безнаковый символ, | ||
| // поэтому преобразуем текущий символ из char в unsigned char | ||
| unsigned char uc = static_cast<unsigned char>(array[read]); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. данное преобразование произойдет неявно, это лишний каст |
||
| // если текущий символ пробельный | ||
| if (std::isspace(uc)) { | ||
|
|
||
| // пропускаем все подряд идущие пробельные символы | ||
| while (read < size && array[read] != '\0') { | ||
| unsigned char c = static_cast<unsigned char>(array[read]); | ||
| if (!std::isspace(c)) { | ||
| break; // текущий символ больше не пробел — выходим | ||
| } | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. проблемы с отступами |
||
| ++read; // пробел — пропускаем и идём дальше | ||
| } | ||
| // теперь когда мы прочитали все пробелы записывыем в write только один пробел | ||
| array[write++] = delimiter; | ||
|
|
||
| } else { | ||
| // Теперь рассматриваем случай когда у нас идут подряд одинаковые символы | ||
| // Текущий символ массива | ||
| char current = array[read]; | ||
| size_t count = 0; // это как счетчик, то есть сколько повторябщихся символов | ||
| // идем пока текущий символ не превзойдет размер массива и | ||
| // символ не конец строки и символ на текущей позиции такой же как и currentт | ||
| while (read < size && array[read] != '\0' && array[read] == current) { | ||
| ++count; | ||
| ++read; | ||
| } | ||
|
|
||
| // Определяем, какой символ писать по правилам | ||
| // в cppreference указано, что isdigit,isupper,islower должно принимать безнаковый символ, | ||
| // поэтому преобразуем текущий символ current из char в unsigned char | ||
| unsigned char cu = static_cast<unsigned char>(current); | ||
| char Char; | ||
|
|
||
| if (std::isdigit(cu)) { // цифры заменяем на '*' | ||
| Char = '*'; | ||
| } else if (std::isupper(cu)) { //прописные латинские не меняем | ||
| Char = current; | ||
| } else if (std::islower(cu)) { // строчные на прописные | ||
| Char = static_cast<char>(std::toupper(cu)); | ||
| } else { // остальное на '_' | ||
| Char = '_'; | ||
| } | ||
|
|
||
| // записываем символ в write | ||
| array[write++] = Char; | ||
|
|
||
| // пишем количество повторений, если count > 1 | ||
| if (count > 1) { | ||
| if (count >= 10) { // Если повторений не менее 10, указывается `0` после символа | ||
| array[write++] = '0'; | ||
| } else { | ||
| // записываем в write число посторений (то есть елси 2222, то 4), | ||
| // Например, если было "2222", то count = 4, и мы должны записать символ '4'. | ||
| // В кодировке ASCII код символа '0' равен 48 | ||
| // Поэтому, чтобы получить символ '4', берём код '0' (48) и прибавляем 4 (48 + 4 = 52 — это код '4') | ||
| array[write++] = static_cast<char>('0' + count); // | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // завершаем строку | ||
| if (write >= size) { | ||
| write = size - 1; | ||
| } | ||
| array[write] = '\0'; | ||
|
|
||
| return write; | ||
| } | ||
|
|
||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| // в метрах | ||
| const double INCH = 0.0254; | ||
| const double FOOT = 0.3048; | ||
| const double CM = 0.01; | ||
|
|
||
| // перевод из дюймов в метры | ||
| double operator"" _in_to_m(long double v) { | ||
| return v * INCH; | ||
| } | ||
| // перевод из дюймов в сантиметры | ||
| double operator"" _in_to_cm(long double v) { | ||
| double m = v * INCH; | ||
| return m / CM; | ||
| } | ||
| // перевод из дюймов в футы | ||
| double operator"" _in_to_ft(long double v) { | ||
| double m = v * INCH; | ||
| return m / FOOT; | ||
| } | ||
|
|
||
| // перевод из футов в метры | ||
| double operator"" _ft_to_m(long double v) { | ||
| return v * FOOT; | ||
| } | ||
| // перевод из футов в сантиметры | ||
| double operator"" _ft_to_cm(long double v) { | ||
| double m = v * FOOT; | ||
| return m / CM; | ||
| } | ||
| // перевод из футов в дюймы | ||
| double operator"" _ft_to_in(long double v) { | ||
| double m = v * FOOT; | ||
| return m / INCH; | ||
| } | ||
|
|
||
| // перевод из сантиметров в метры | ||
| double operator"" _cm_to_m(long double v) { | ||
| return v * CM; | ||
| } | ||
| // перевод из сантиметров в дюймы | ||
| double operator"" _cm_to_in(long double v) { | ||
| double m = v * CM; | ||
| return m / INCH; | ||
| } | ||
| // перевод из сантиметров в футы | ||
| double operator"" _cm_to_ft(long double v) { | ||
| double m = v * CM; | ||
| return m / FOOT; | ||
| } | ||
|
|
||
| // перевод из метров в сантиметры | ||
| double operator"" _m_to_cm(long double v) { | ||
| return v / CM; | ||
| } | ||
| // перевод из метров в дюймы | ||
| double operator"" _m_to_in(long double v) { | ||
| return v / INCH; | ||
| } | ||
| // перевод из метров в футы | ||
| double operator"" _m_to_ft(long double v) { | ||
| return v / FOOT; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,30 @@ | ||
| #include <cstddef> | ||
| #include <stdexcept> | ||
|
|
||
|
|
||
| // value - целое число, его нужно вывести в двоичной форме | ||
| // bytes типа size_t потому что bytes это количсевто байт | ||
| void PrintBits(long long value, size_t bytes) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| // по условию мы не можем выполнить функцию когда у нас | ||
| // количсевто байт = 0, либо количесвто байт > 8 | ||
| if (bytes == 0 || bytes > 8) { | ||
| return; | ||
| } | ||
| // Считаем общее количсевто бит, 1 байт = 1 бит | ||
| size_t bits = bytes * 8; | ||
| // выводим префикс "0b", дальше будет идти предствление числа | ||
| std::cout << "0b"; | ||
| // цикл будет выполняться bits раз | ||
| for (size_t i = 0; i < bits; ++i) { | ||
| size_t bit_index = bits - 1 - i; | ||
| // побитовый сдвиг, сравниваем младший бит с 1 и выводим результат | ||
| std::cout << ((value >> bit_index) & 1); | ||
|
|
||
| // если i + 1 делится на 4 без остатка и это не полседний бит, | ||
| // ставим "'" | ||
| if ((i + 1) % 4 == 0 && (i + 1) != bits) { | ||
| std::cout << "'"; | ||
| } | ||
| } | ||
| // перевод строки | ||
| std::cout << '\n'; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,85 @@ | ||
| #include <stdexcept> | ||
| #include <iostream> | ||
| #include <iomanip> | ||
| #include <cmath> | ||
|
|
||
|
|
||
| void SolveQuadratic(int a, int b, int c) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } | ||
| // первый случай: если a = b = c = 0, то уравнение примнимает бесконченое количесвто решений | ||
| if (a == 0 && b == 0 && c == 0) { | ||
| std::cout << "infinite solutions"; | ||
| return; | ||
| } | ||
|
|
||
| // второй случай: если a = b = 0, то уравнение решений не имеет | ||
| if (a == 0 && b == 0) { | ||
| std::cout << "no solutions"; | ||
| return; | ||
| } | ||
|
|
||
| std::cout << std::setprecision(6); | ||
|
|
||
| // третий случай: a == 0, b != 0 → b*x + c = 0 | ||
| if (a == 0) { | ||
| double x = -static_cast<double>(c) / static_cast<double>(b); // x = -c / b | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. лишний каст |
||
|
|
||
| // Убираем возможный "-0" | ||
| if (x == -0.0) { | ||
| x = 0.0; | ||
| } | ||
|
|
||
| std::cout << x; | ||
| return; | ||
| } | ||
|
|
||
| // 4) четвертый случай: a неравно 0, то есть уже само квадартное уравнение | ||
| double A = static_cast<double>(a); | ||
| double B = static_cast<double>(b); | ||
| double C = static_cast<double>(c); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. это лишние переменные, достаточно было бы 4.0 в дискриминанте или каст одного из значений у слагаемых по месту использования |
||
|
|
||
| // Дискриминант | ||
| double D = B * B - 4 * A * C; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. модет тогда стоит назвать discriminant переменную? |
||
|
|
||
| // Нет вещественных корней | ||
| if (D < 0) { | ||
| std::cout << "no solutions"; | ||
| return; | ||
| } | ||
|
|
||
| // Один вещественный корень | ||
| if (D == 0) { | ||
| double root = -B / (2 * A); | ||
| double x = static_cast<double>(root); | ||
|
|
||
| // Убираем "-0" | ||
| if (x == -0.0) { | ||
| x = 0.0; | ||
| } | ||
|
|
||
| std::cout << x; | ||
| return; | ||
| } | ||
|
|
||
| // если D > 0, то имеем два различных корня | ||
| double sqrtD = std::sqrt(D); | ||
|
|
||
| double root1 = (-B - sqrtD) / (2 * A); | ||
| double root2 = (-B + sqrtD) / (2 * A); | ||
|
|
||
| double x1 = static_cast<double>(root1); | ||
| double x2 = static_cast<double>(root2); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| // Убираем "-0" для каждого корня | ||
| if (x1 == -0.0) { | ||
| x1 = 0.0; | ||
| } | ||
| if (x2 == -0.0) { | ||
| x2 = 0.0; | ||
| } | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. в C++ 0.0 строго определен, что за -0.0 ? |
||
|
|
||
| // выводим так, чтобы x1 < x2 | ||
| if (x1 > x2) { | ||
| std::swap(x1, x2); | ||
| } | ||
|
|
||
| std::cout << x1 << ' ' << x2; | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лишний каст, достаточно явно кастовать только один операнд, второй будет неявно преобразован, необходимо использовать данную возможность языка и не писать лишний код