public string EvaluateExpression(string expressions) {//计算表达式 expressions = expressions + '#'; //存储运算值的栈 myStack operation = new myStack(); operation.Push(0); //存储运算符的栈 myStack TR = new myStack(); TR.Push('#'); char c, theta; char[] num = new char[20]; int j = 0; for (int i = 0; i < expressions.Length; i++) { c = Convert.ToChar(expressions[i]); int a, b; if (Char.IsDigit(c)) { num[j++] = c; continue; } else { if (j != 0) { num[j] = Convert.ToChar(0); operation.Push(strToNum(num)); j = 0; } switch (CompareTR(TR, c)) { case '<': { TR.Push(c); break; } case '>': { theta = Convert.ToChar(TR.Pop()); b = Convert.ToInt32(operation.Pop()); a = Convert.ToInt32(operation.Pop()); operation.Push(Operate(a, theta, b)); break; } case '=': { c = Convert.ToChar(TR.Pop()); break; } } } } return(Convert.ToString(operation.Pop())); }
private char CompareTR(myStack S, char c) {//判断优先级 char iResult = ' '; switch (S.GetTop()) { case '+': { if (c == '*' || c == '/' || c == '(') { return('<'); } else if (c == '+' || c == '-' || c == ')' || c == '#') { return('>'); } break; } case '-': { if (c == '*' || c == '/' || c == '(') { return('<'); } else if (c == '+' || c == '-' || c == ')' || c == '#') { return('>'); } break; } case '*': { if (c == '(') { return('<'); } else if (c == '+' || c == '-' || c == '*' || c == '/' || c == ')' || c == '#') { return('>'); } break; } case '/': { if (c == '(') { return('<'); } else if (c == '+' || c == '-' || c == '*' || c == '/' || c == ')' || c == '#') { return('>'); } break; } case '(': { if (c == ')') { return('='); } else { return('<'); } break; } case ')': { return('>'); break; } case '#': { if (c == '#') { return('='); } else { return('<'); } break; } } return(iResult); }