首先自己百度下面两个名词
前缀表达式、后缀表达式
我们计算机 能直接计算的是后缀表达式。
前缀表达式:1+2*3+4 = 11
后缀表达式:1 2 3 *+4+ = 11
///下面是计算后缀表达式:/// 将前缀表达式转换为后缀表达式 /// /// ///private string InfixToSuffix(string strInfix) { LinkStack ls = new LinkStack(); System.Text.StringBuilder sb = new StringBuilder(200); string str = strInfix.Trim(); foreach(var word in str) { if (char.IsNumber(word)) { sb.Append(word); } else { //非数字,先加个空格。 sb.Append(' '); if (word == '(') { ls.Push(word); } else if (word == ')') { while (!ls.Empty()) { char ch = (char)ls.Pop(); if (ch == '(') { break; } sb.Append(ch); } } else if (word == '+' || word == '-') { while(!ls.Empty()) { char ch = (char)ls.Top(); if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { sb.Append((char)ls.Pop()); } else if (ch == '(') { break; } } ls.Push(word); } else if (word == '*' || word == '/') { while (!ls.Empty()) { char ch = (char)ls.Top(); if (ch == '*' || ch == '/') { sb.Append((char)ls.Pop()); } else if (ch == '+' || ch == '-' || ch == '(') { break; } } ls.Push(word); } else { } } } while (!ls.Empty()) { sb.Append(ls.Pop()); } return sb.ToString(); }
////// 计算后缀表达式 /// /// ///private int CalculateSuffix(string strSuffix) { LinkStack ls = new LinkStack(); int num=0; Boolean numState = false; foreach (var word in strSuffix) { if (char.IsNumber(word)) { numState = true; num = num*10+int.Parse(word.ToString()); } else { //将数入栈 if (numState == true) { ls.Push(num); num = 0; } numState=false; if (word != ' ') { //忽略空白 int num2 = (int)ls.Pop(), num1 = (int)ls.Pop(); switch(word) { case '+': ls.Push(num1 + num2); break; case '-': ls.Push(num1 - num2); break; case '*': ls.Push(num1 * num2); break; case '/': ls.Push(num1 / num2); break; } } } } return (int)ls.Pop(); }