中序表达式求值

对于一个数学表达式,语言编译系统是怎么求值的呢?

通常的做法是对一个数学中序表达式求逆波兰式(后序表达式),然后再求值。

 

笔者用C#写了一个中序表达式求值的类,以供参考

 

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Expression { class Exp { private string originalExp=null; private string nipolanExp=null; private void tran(string expression)//求逆波兰式 { originalExp = expression; Stack<string> stack=new Stack<string>(); int i = 0; char ch; string numStr=null; while (i != originalExp.Length) { ch = originalExp[i]; if (ch >= '0' && ch <= '9') { numStr += ch.ToString(); if (i==originalExp.Length-1||originalExp[i + 1] < '0' || originalExp[i + 1] > '9') { nipolanExp += numStr + "$"; numStr = null; } } else if (ch == '(') { string str = ch.ToString(); stack.Push(str); } else if (ch == ')') { while (stack.Peek() != "(")//栈为string型 { nipolanExp += stack.Pop(); } stack.Pop(); } else if (ch == '+' || ch == '-') { while (stack.Count!=0 && stack.Peek()!="(") { nipolanExp += stack.Pop(); } stack.Push(ch.ToString()); } else if (ch == '*' || ch == '/') { while (stack.Count!=0&&(stack.Peek() == "*" || stack.Peek() =="/")) { nipolanExp += stack.Pop(); } stack.Push(ch.ToString()); } i++; } while(stack.Count!=0) { nipolanExp += stack.Pop(); } } public int CompValue(string expression)//由逆波兰式求值 { tran(expression); int sum = 0; int i = 0; Stack<int> stackGetValue=new Stack<int>(); char chr; while (i != nipolanExp.Length) { chr = nipolanExp[i]; //Console.WriteLine(chr.ToString()); if (chr >= '0' && chr <= '9') { string strVal = null; while (chr != '$') { strVal += chr.ToString(); //Console.WriteLine(strVal+"<<<<"); i++; chr = nipolanExp[i]; } stackGetValue.Push(Convert.ToInt32(strVal)); //Console.WriteLine("....."+stackGetValue.Peek()); } else { int temp = 0; int intTop = 0; switch (chr) { case '+': intTop = stackGetValue.Pop(); temp = stackGetValue.Pop()+intTop; stackGetValue.Push(temp); break; case '-': intTop = stackGetValue.Pop(); temp = stackGetValue.Pop() - intTop; stackGetValue.Push(temp); break; case '*': intTop = stackGetValue.Pop(); temp = stackGetValue.Pop() * intTop; stackGetValue.Push(temp); break; case '/': intTop = stackGetValue.Pop(); if (intTop != 0) { temp = stackGetValue.Pop() / intTop; stackGetValue.Push(temp); } else Console.WriteLine("0不能作除数!"); break; } } i++; } sum = stackGetValue.Pop(); return sum; } public void SetOringalExp(string expression) { originalExp = expression; } public string GetNipolanExp() { string expStr = nipolanExp; return expStr; } } }

 

控制台代码:

 

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Expression { class Program { static void Main(string[] args) { string s = "200*(10+20)-5"; Exp ts = new Exp(); int result = ts.CompValue(s); string str = ts.GetNipolanExp(); Console.WriteLine(s); Console.WriteLine(str); Console.WriteLine("计算结果为" + result.ToString()); Console.Read(); } } }

你可能感兴趣的:(String,C#,null,Class,语言)