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。任何可以帮助我。谢谢你。