0
string expr = Text1.Text;
string[] num = Regex.Split(expr, @"\(|\)|\-|\+|\*|\/").Where(s => !String.IsNullOrEmpty(s)).ToArray(); // get Array for numbers
string[] op = Regex.Split(expr, @"\(|\)|\d{1,3}").Where(s => !String.IsNullOrEmpty(s)).ToArray(); // get Array for mathematical operators +,-,/,*
int firstVal = 0;
int numCtr = 0;            
int lastVal = 0;   
string  lastOp = ""; 
int num2Cntr = 0;

foreach (string n in num)
{
    numCtr++;
    if (numCtr == 1)
    {
       lastVal = int.Parse(n); 
    }      
    else
    {
        if (!String.IsNullOrEmpty(lastOp)) 
    {
    switch (lastOp)
    {
    case "+":
    lastVal = lastVal + int.Parse(n) ;
    break;
    case "-":
    lastVal = lastVal - int.Parse(n);
    break;
    case "*":
    lastVal = lastVal * int.Parse(n);
    break;
    case "/":
    lastVal = lastVal / int.Parse(n);
    break;
    case "(":
    numCtr++;
    foreach (string a in num)
    {
    num2Cntr++;

    if (num2Cntr == 1)
    {
    firstVal = int.Parse(a);
    }
    else
    {
    if (!String.IsNullOrEmpty(lastOp))
    {
    switch (lastOp)
    {
    case "+":                                             firstVal = firstVal + int.Parse(a);
                                        break;
case "-":
                                        firstVal = firstVal - int.Parse(a);
                                        break;
case "*":
                                        firstVal = firstVal * int.Parse(a);
                                        break;
case "/":
                                        firstVal = firstVal / int.Parse(a);
                                        break;
    }
       }
      }    
     }
break;
case ")":
lastVal = lastVal + firstVal;
return;
}
   }
  }
int opCtr = 0;
foreach (string o in op)
{
opCtr++;
if (opCtr == numCtr) 
{ 
lastOp = o; 
break;
}
}
}

Text2.Text = lastVal.ToString();

1)How to set precedence high for parentheses? 2) I am trying to set precedence because the expression entered should evaluate as like binary tree. First it must take precedence high for parentheses and then for operators. 3) My code above works fine and evaluate expression from left to right. i.e, 5+6+7=18 but if i give 5+(5+5)+(5*2) i am getting result as 40. But exact result is 25. can any help me. thank you.

  • 1
    Where does it fail? On what line? How? Any errors? Braces? What braces? Where? Priority? Priority of what? Explain clearly what it is that is the problem. – Arran Jun 24 '13 at 10:24
  • 3
    eugh; that is virtually unreadable due to crazy layout... it is not at all clear what you are trying to do, and in what scenarios it fails - can you clarify? – Marc Gravell Jun 24 '13 at 10:27
  • @Arran: There is no errors i will get output for expression 5+10*9-10. but i wont get output for 5+(5+5) i will get output as 5. – user2499557 Jun 24 '13 at 10:32
  • The for-loop at the end seems to be a very complicated way of writing `lastOp = op[numCtr - 1]`. – Marcelo Cantos Jun 24 '13 at 10:46
  • Maybe this can help: http://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-in-c/9329509#9329509 of course, you need to adapt it to C#. – Henrik Jun 24 '13 at 10:47

1 Answers1

1

The best way to do it is by not doing it yourself :), There is a simple way of expression evaluation using DataTable under this link you can find examples.

Or in this example:

[TestMethod]
public void test()
{
    var evalTable = new DataTable();
    using (var evalExpressionColumn = new DataColumn("EvaluateExpression", typeof(double), "0"))
    {
        evalTable.Columns.Add(evalExpressionColumn);
    }
    evalTable.Rows.Add(0);
    evalTable.Columns[0].Expression = "(5 + 4 ) * 8";
    //Note: Evaluate expression.
    var res = Convert.ToDouble(evalTable.Rows[0]["EvaluateExpression"]);
    Assert.AreEqual(72, res);
}

More Complex calculations are also supported the syntax is defined in the link I supplied.

Sergey Kucher
  • 4,140
  • 5
  • 29
  • 47