Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ExpressionEvaluation
- {
- class Program
- {
- static string expression = "(2.2 * 3 + 2)*5-(3*4)/4"; // Insert an (correct) expression to evaluate, for example: (600-500+2)/2
- static Stack<char> stOperator = new Stack<char>();
- static Stack<double> stOperand = new Stack<double>();
- static void Main(string[] args)
- {
- expression = expression.Replace(" ", String.Empty).Replace(",", ".");
- EvaluateExpression(expression);
- Console.WriteLine($"Input: {expression}");
- Console.WriteLine($"Output: {((stOperand.Count==1)?(stOperand.Pop()).ToString().Replace(",", "."):"ERROR!")}");
- }
- static void EvaluateExpression(string e)
- {
- string number = String.Empty;
- for (int i = 0; i < e.Length; i++)
- {
- char c = e[i];
- if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')')
- {
- if (number != String.Empty) { stOperand.Push(Parse(number)); number = String.Empty; }
- if (c == ')')
- {
- while (stOperator.Count > 0 && stOperator.Peek() != '(')
- {
- EvaluateNext();
- }
- stOperator.Pop();
- continue;
- }
- if (stOperator.Count > 0)
- {
- if ((stOperator.Peek() == '*' || stOperator.Peek() == '/') && c != '(') EvaluateNext();
- }
- stOperator.Push(c);
- continue;
- }
- number += c.ToString();
- }
- if (number != String.Empty) { stOperand.Push(Parse(number)); number = String.Empty; }
- while (stOperator.Count > 0)
- {
- EvaluateNext();
- }
- }
- static void EvaluateNext()
- {
- char o = stOperator.Pop();
- double b = stOperand.Pop();
- double a = stOperand.Pop();
- if (stOperator.Count > 0)
- {
- if (stOperator.Peek() == '-' && o != '*' && o != '/') b = -b;
- }
- switch (o)
- {
- case '+':
- stOperand.Push(a + b);
- break;
- case '-':
- stOperand.Push(a - b);
- break;
- case '*':
- stOperand.Push(a * b);
- break;
- case '/':
- stOperand.Push(a / b);
- break;
- }
- }
- static double Parse(string number)
- {
- return (Double.Parse(number, System.Globalization.CultureInfo.InvariantCulture));
- }
- }
- }
Add Comment
Please, Sign In to add comment