Guest User

Untitled

a guest
Apr 25th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ExpressionEvaluation
  8. {
  9. class Program
  10. {
  11. static string expression = "(2.2 * 3 + 2)*5-(3*4)/4"; // Insert an (correct) expression to evaluate, for example: (600-500+2)/2
  12.  
  13. static Stack<char> stOperator = new Stack<char>();
  14. static Stack<double> stOperand = new Stack<double>();
  15.  
  16. static void Main(string[] args)
  17. {
  18. expression = expression.Replace(" ", String.Empty).Replace(",", ".");
  19.  
  20. EvaluateExpression(expression);
  21.  
  22. Console.WriteLine($"Input: {expression}");
  23. Console.WriteLine($"Output: {((stOperand.Count==1)?(stOperand.Pop()).ToString().Replace(",", "."):"ERROR!")}");
  24. }
  25.  
  26. static void EvaluateExpression(string e)
  27. {
  28. string number = String.Empty;
  29.  
  30. for (int i = 0; i < e.Length; i++)
  31. {
  32. char c = e[i];
  33.  
  34. if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')')
  35. {
  36. if (number != String.Empty) { stOperand.Push(Parse(number)); number = String.Empty; }
  37.  
  38. if (c == ')')
  39. {
  40. while (stOperator.Count > 0 && stOperator.Peek() != '(')
  41. {
  42. EvaluateNext();
  43. }
  44.  
  45. stOperator.Pop();
  46.  
  47. continue;
  48. }
  49.  
  50. if (stOperator.Count > 0)
  51. {
  52. if ((stOperator.Peek() == '*' || stOperator.Peek() == '/') && c != '(') EvaluateNext();
  53. }
  54.  
  55. stOperator.Push(c);
  56.  
  57. continue;
  58. }
  59.  
  60. number += c.ToString();
  61. }
  62.  
  63. if (number != String.Empty) { stOperand.Push(Parse(number)); number = String.Empty; }
  64.  
  65. while (stOperator.Count > 0)
  66. {
  67. EvaluateNext();
  68. }
  69. }
  70.  
  71. static void EvaluateNext()
  72. {
  73. char o = stOperator.Pop();
  74.  
  75. double b = stOperand.Pop();
  76. double a = stOperand.Pop();
  77.  
  78. if (stOperator.Count > 0)
  79. {
  80. if (stOperator.Peek() == '-' && o != '*' && o != '/') b = -b;
  81. }
  82.  
  83. switch (o)
  84. {
  85. case '+':
  86. stOperand.Push(a + b);
  87. break;
  88. case '-':
  89. stOperand.Push(a - b);
  90. break;
  91. case '*':
  92. stOperand.Push(a * b);
  93. break;
  94. case '/':
  95. stOperand.Push(a / b);
  96. break;
  97. }
  98. }
  99.  
  100. static double Parse(string number)
  101. {
  102. return (Double.Parse(number, System.Globalization.CultureInfo.InvariantCulture));
  103. }
  104. }
  105. }
Add Comment
Please, Sign In to add comment