Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cstring>
  4. #pragma warning(disable:4996)
  5.  
  6. using namespace std;
  7.  
  8. char ** words = new char*[101];
  9. char ** wordsBracket = new char*[101];
  10.  
  11. double getResult(int wordFrom, int wordTo, int wordsCount) {
  12. double result = 0;
  13. double lastBracketResult = 0;
  14. for (int i = wordFrom; i < wordTo; i++)
  15. {
  16. if (strcmp(wordsBracket[i], "+") == 0) {
  17. if (strcmp(wordsBracket[i], ")") != 0)
  18. result += atof(wordsBracket[i - 1]);
  19. else
  20. result += lastBracketResult;
  21. }
  22. else if(strcmp(wordsBracket[i], "*") == 0) {
  23. int next = i + 1;
  24. double multiplyResult;
  25. double nextBracket = 0;
  26. if (strcmp(wordsBracket[i-1], ")") != 0)
  27. multiplyResult = atof(wordsBracket[i - 1]);
  28. else
  29. multiplyResult = lastBracketResult;
  30. do {
  31. if (strcmp(wordsBracket[next], "(") == 0) {
  32. int secondBracket = 0;
  33. while (strcmp(wordsBracket[secondBracket], ")"))
  34. secondBracket++;
  35. multiplyResult *= getResult(next + 1, secondBracket, wordsCount);
  36. next = secondBracket;
  37. }
  38. else if (strcmp(wordsBracket[next], "*") != 0) {
  39. multiplyResult *= atof(wordsBracket[next]);
  40. }
  41. next++;
  42. } while (next < wordTo && strcmp(wordsBracket[next], "+") != 0);
  43. result += multiplyResult;
  44. i = next;
  45. }
  46. else if (strcmp(wordsBracket[i], "(") == 0) {
  47. int secondBracket = 0;
  48. while (strcmp(wordsBracket[secondBracket], ")"))
  49. secondBracket++;
  50. if(secondBracket == wordTo - 1)
  51. result += getResult(i + 1, secondBracket, wordsCount);
  52. else
  53. lastBracketResult = getResult(i + 1, secondBracket, wordsCount);
  54. }
  55.  
  56. else if(i == wordTo - 1){
  57. result += atof(wordsBracket[i]);
  58. }
  59. }
  60. return result;
  61. }
  62.  
  63. int main(int argc, char ** argv) {
  64. char * str = new char[101];
  65. char ** wordsAfterMultyPly = new char*[101];
  66. char * word;
  67. char * plus = new char[2];
  68. strcpy(plus, "+");
  69. char * mult = new char[2];
  70. strcpy(mult, "*");
  71. int newWordsCount = 0;
  72. int wordsCount = 0;
  73. double result = 0;
  74. cin.getline(str, 101);
  75. word = strtok(str, " ");
  76. do {
  77. wordsBracket[wordsCount] = word;
  78. wordsCount++;
  79. } while ((word = strtok(NULL, " ")) != NULL);
  80.  
  81. result = getResult(0, wordsCount, wordsCount);
  82.  
  83. cout << result;
  84. system("pause");
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement