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)如何为括号设置高优先级?2)我正在尝试设置优先级,因为输入的表达式应该像二叉树一样评估。首先,它必须优先考虑括号,然后是运算符。3)我上面的代码工作正常,从左到右评估表达式。即,5 + 6 + 7 = 18,但如果我给出5 +(5 + 5)+(5 * 2),我得到的结果为40。但确切的结果是25。任何可以帮助我。谢谢你。

4

1 回答 1

1

最好的方法是不要自己做 :),在此链接下有一种使用DataTable进行表达式评估的简单方法,您可以找到示例。

或者在这个例子中:

[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);
}

还支持更复杂的计算,语法在我提供的链接中定义。

于 2013-06-24T10:37:01.997 回答