abubaca

calc

Dec 24th, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.45 KB | None | 0 0
  1. #include <conio.h>
  2. #include "windows.h"
  3. #include <iostream>
  4. #include <vector>
  5. #include <string>
  6. #include <functional>
  7. #include <cmath>
  8.  
  9. using namespace std;
  10. //размер окна консоли в символах
  11. #define WIDTH 80
  12. #define HEIGHT 30
  13. const double PI = 3.141592653589793238463; //задание константы PI
  14. HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE); //получение дескриптора экранного буфера(требуется для функций консоли из windows.h)
  15.  
  16. void print(string &text, int x, int y) //вывод текста начиная с указанных координат. строка передаётся через ссылку чтобы избежать дублирования строки в памяти
  17. {
  18.     COORD pos; //задача координат
  19.     pos.X = x;
  20.     pos.Y = y;
  21.     SetConsoleCursorPosition(hCon, pos); //установка курсора в заданную позицию
  22.     cout << text; //вывод строки
  23. }
  24.  
  25. class menu
  26. {
  27.     vector <string> points; //вектор строк. пункты меню
  28.     vector <function<void()>> actions; //вектор указателей на функции, соответствующие пунктам меню. functional используется для передачи указателей на функций как часть класса
  29.     int point = 0; //текущий пункт меню
  30.     void show() //вывод меню на экран. предполагается, что добавлен хотя бы один пункт меню
  31.     {
  32.         system("cls"); //очистка окна консоли
  33.         int xMiddle = WIDTH / 2; //середина консольного окна
  34.         int yPart = HEIGHT / ((int)points.size() + 1); //вычисление высоты для вывода пунктов меню
  35.         for (int i = 0; i < (int)points.size(); i++) //здесь и на протяжении всего текста программы преобразование size_t в int для избегания warningов
  36.         {
  37.             if (i == point) //отображение текущего выбранного пункта меню
  38.             {
  39.                 string temp = "<<" + points[i] + ">>";
  40.                 print(temp, xMiddle - (int)temp.length() / 2, yPart*(i + 1)); //вывод пунта меню со смещением по x для центрации и по y в соответствии с номером
  41.             }
  42.             else
  43.                 print(points[i], xMiddle - (int)points[i].length() / 2, yPart*(i + 1));
  44.         }
  45.     }
  46.     void up()
  47.     {
  48.         point = point == 0 ? (int)points.size() - 1 : point - 1; //переключение на один пункт вверх
  49.     }
  50.     void down()
  51.     {
  52.         point = point == (int)points.size() - 1 ? 0 : point + 1; //переключение на один пункт вниз
  53.     }
  54.     void enter()
  55.     {
  56.         actions[point](); //выполнение действия текущего пункта
  57.     }
  58. public: //функции, доступные извне объекта
  59.     void add(string newP, function<void()> newA) //добавление нового пункта меню
  60.     {
  61.         points.push_back(newP);
  62.         actions.push_back(newA);
  63.     }
  64.     void get() //обработка нажатий клавиш
  65.     {
  66.         show(); //предварительный вывод меню
  67.         int button; //код введёной клавиши
  68.         while (true) //бесконечный цикл для обработки нажатий клавиш
  69.         {
  70.             button = _getch(); //получение кода нажатой клавиши без её вывода в буфер консоли
  71.             switch (button) //обработка нажатых клавиш
  72.             {
  73.             case 72: //стрелка вверх
  74.                 up();
  75.                 break;
  76.             case 80: //стрелка вниз
  77.                 down();
  78.                 break;
  79.             case 13: //enter
  80.                 enter();
  81.                 break;
  82.             case 27: //esc закрытие меню
  83.                 return;
  84.                 break;
  85.             }
  86.             show(); //вывод нового меню
  87.         }
  88.     }
  89. };
  90.  
  91. void calck_sin() //функция считывания аргумента, вычисления и вывода значения синуса
  92. {
  93.     system("cls");
  94.     int xMiddle = WIDTH / 2;
  95.     string output; //формирование строки для вывода
  96.     output = "sin(x)";
  97.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 1); //выведение строк последовательно, с центром в центре окна
  98.     output = "x(grad)=";
  99.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2);
  100.     double x;
  101.     cin >> x; //считывание аргумента
  102.     output = "sin(" + to_string(x) + ")=" + to_string(sin((x * PI) / 180)); //подсчёт значения функции. преобразование значения в радианы для использования с функциями библиотеки cmath
  103.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 + 1);
  104.     int input = 0; //хранение последней нажатой клавиши
  105.     while (input != 27 && input != 13) //выход в меню при нажатии esc или enter
  106.     {
  107.         input = _getch();
  108.     }
  109. }
  110.  
  111. void calck_cos() //функция считывания аргумента, вычисления и вывода значения косинуса
  112. {
  113.     system("cls");
  114.     int xMiddle = WIDTH / 2;
  115.     string output;
  116.     output = "cos(x)";
  117.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 1);
  118.     output = "x(grad)=";
  119.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2);
  120.     double x;
  121.     cin >> x;
  122.     output = "cos(" + to_string(x) + ")=" + to_string(cos((x * PI) / 180));
  123.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 + 1);
  124.     int input = 0;
  125.     while (input != 27 && input != 13)
  126.     {
  127.         input = _getch();
  128.     }
  129. }
  130.  
  131. void calck_tg() //функция считывания аргумента, вычисления и вывода значения тангенса
  132. {
  133.     system("cls");
  134.     int xMiddle = WIDTH / 2;
  135.     string output;
  136.     output = "tg(x)";
  137.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 1);
  138.     output = "x(grad)=";
  139.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2);
  140.     double x;
  141.     cin >> x;
  142.     output = "tg(" + to_string(x) + ")=" + to_string(tan((x * PI) / 180));
  143.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 + 1);
  144.     int input = 0;
  145.     while (input != 27 && input != 13)
  146.     {
  147.         input = _getch();
  148.     }
  149. }
  150.  
  151. void calck_sqrt() //функция вычисления корня
  152. {
  153.     system("cls");
  154.     int xMiddle = WIDTH / 2;
  155.     string output;
  156.     output = "sqrt(x)";
  157.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 1);
  158.     output = "x=";
  159.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2);
  160.     double x;
  161.     cin >> x;
  162.     output = "sqrt(" + to_string(x) + ")=" + to_string(sqrt(x));
  163.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 + 1);
  164.     int input = 0;
  165.     while (input != 27 && input != 13)
  166.     {
  167.         input = _getch();
  168.     }
  169. }
  170.  
  171. void calck_simple() //функция для рассчёта функций с двумя аргументами, задать которые можно одним символом
  172. {
  173.     system("cls");
  174.     int xMiddle = WIDTH / 2;
  175.     string output;
  176.     output = "You can chouse from actions: +, -, *, / and ^";
  177.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 3);
  178.     output = "Enter action:";
  179.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 2);
  180.     int action = 0; //хранение текущего действия
  181.     while (action != '+' && action != '-' && action != '*' && action != '/' && action != '^')  //ожидание ввода одного из поддерживаемых действий
  182.     {
  183.         action = _getch();
  184.         if (action == '+' || action == '-' || action == '*' || action == '/' || action != '^') //вывод действия если оно поддерживается
  185.             cout << (char)action;
  186.     }
  187.     output = "x";
  188.     output += (char)action; //при попытке написать в одну строку ошибка
  189.     output += "y";
  190.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 - 1);
  191.     double x, y, result;
  192.     output = "x=";
  193.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2);
  194.     cin >> x; //считывание x
  195.     output = "y=";
  196.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 + 1);
  197.     cin >> y; //считывание y
  198.     switch (action) //подсчёт результата
  199.     {
  200.     case '+':
  201.         result = x + y;
  202.         break;
  203.     case '-':
  204.         result = x - y;
  205.         break;
  206.     case '*':
  207.         result = x * y;
  208.         break;
  209.     case '/':
  210.         result = x / y;
  211.         break;
  212.     case '^':
  213.         result = pow(x, y);
  214.         break;
  215.     }
  216.     output = to_string(x);
  217.     output += (char)action;
  218.     output += to_string(y) + "=" + to_string(result);
  219.     print(output, xMiddle - (int)output.length() / 2, HEIGHT / 2 + 2);
  220.     int input = 0;
  221.     while (input != 27 && input != 13)
  222.     {
  223.         input = _getch();
  224.     }
  225. }
  226.  
  227. int main()
  228. {
  229.     string resize = "mode " + to_string(WIDTH) + ", " + to_string(HEIGHT); //формирование строки для изменения размера консоли и отключения полосы прокрутки
  230.     system(resize.c_str()); //выполнение системной команды для изменения размера консоли с предварительным преобразованием строки в C-style строку(требуется как аргумент в system)
  231.     setlocale(LC_ALL, "Russian"); //включение русской кодировки
  232.     //формирование цвета текста и фона консоли http://vsokovikov.narod.ru/New_MSDN_API/Console/scrbuf.htm#attrib_char_cons
  233.     SetConsoleTextAttribute(hCon, BACKGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY); //изменение цвета текста и фона консоли
  234.     menu complex_functions; //меню для сложных функций
  235.     complex_functions.add("sin", calck_sin);
  236.     complex_functions.add("cos", calck_cos);
  237.     complex_functions.add("tg", calck_tg);
  238.     complex_functions.add("sqrt", calck_sqrt);
  239.     menu main_menu;//главное меню
  240.     main_menu.add("complex functions", bind(&menu::get, complex_functions)); //передача указателя на функцию часть класса
  241.     main_menu.add("simple function", calck_simple);
  242.     main_menu.add("exit", bind(exit,0)); //преобразование void (*)(int) в void(*)() с предопределением аргумента
  243.     while (true) //запрет выхода по esc из главного меню
  244.         main_menu.get();
  245. }
Advertisement
Add Comment
Please, Sign In to add comment