Advertisement
Guest User

Untitled

a guest
May 19th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cmath>
  4. #include <list>
  5.  
  6. int charToInt(char c) {
  7. return c - '0';
  8. }
  9.  
  10. int check(char c)
  11. {
  12. return (c == '2' || c == '3' || c == '4' || c == '+' || c == '*') ? 1 : 0;
  13. }
  14.  
  15. int calculate(char op, int a, int b) {
  16. if (op == '+') {
  17. return a + b;
  18. }
  19. else if (op == '*') {
  20. return a * b;
  21. }
  22. }
  23.  
  24. int result(std::string string) {
  25. std::list<int> stack;
  26.  
  27. for (int i = 0; i < string.length(); i++) {
  28. char token = string[i];
  29.  
  30. if (!check(token)) return -1;
  31.  
  32. if (token >= '0' && token <= '9') {
  33. stack.push_back(charToInt(token));
  34. }
  35. else {
  36. int a = stack.back();
  37. stack.pop_back();
  38. int b = stack.back();
  39. stack.pop_back();
  40. int result = calculate(token, a, b);
  41. stack.push_back(result);
  42. }
  43.  
  44. }
  45.  
  46. return stack.back();
  47. };
  48.  
  49. int main()
  50. {
  51. std::string string;
  52.  
  53. setlocale(LC_ALL, "russian");
  54.  
  55. std::cout << "Ваше выражение: " << std::endl;
  56. std::cin >> string;
  57.  
  58. std::cout << result(string) << std::endl;
  59.  
  60. system("pause");
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement