• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

逆波兰表达式解数学运算(c#)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
逆波兰表达式解数学运算 感谢作者  http://blog.csdn.net/liuyuxusuixiang/article/details/25289715
public class TCalculator
    {
        Dictionary<char, int> priorities = null;
        const string operators = "+-*/%^";
        public TCalculator()
        {
            priorities = new Dictionary<char, int>();
            priorities.Add('#', -1);
            priorities.Add('+', 0);
            priorities.Add('-', 0);
            priorities.Add('*', 1);
            priorities.Add('/', 1);
            priorities.Add('%', 1);
            priorities.Add('^', 2);
        }

        double Compute(double leftNum, double rightNum, char op)
        {
            switch (op)
            {
                case '+': return leftNum + rightNum;
                case '-': return leftNum - rightNum;
                case '*': return leftNum * rightNum;
                case '/': return leftNum / rightNum;
                case '%': return leftNum % rightNum;
                case '^': return Math.Pow(leftNum, rightNum);
                default: return 0;
            }
        }

        bool IsOperator(char op)
        {
            return operators.IndexOf(op) >= 0;
        }

        bool IsLeftAssoc(char op)
        {
            return op == '+' || op == '-' || op == '*' || op == '/' || op == '%';
        }

        Queue<object> PreOrderToPostOrder(string expression)
        {
            var result = new Queue<object>();
            var operatorStack = new Stack<char>();
            operatorStack.Push('#');
            char top, cur, tempChar;
            string tempNum;
            if (expression[0] == '-') expression = '0' + expression;

            for (int i = 0, j; i < expression.Length; )
            {
                cur = expression[i++];
                top = operatorStack.Peek();

                if (cur == '(')
                {
                    operatorStack.Push(cur);
                }
                else
                {
                    if (IsOperator(cur))
                    {
                        while (IsOperator(top) && ((IsLeftAssoc(cur) && priorities[cur] <= priorities[top])) || (!IsLeftAssoc(cur) && priorities[cur] < priorities[top]))
                        {
                            result.Enqueue(operatorStack.Pop());
                            top = operatorStack.Peek();
                        }
                        operatorStack.Push(cur);
                    }
                    else if (cur == ')')
                    {
                        while (operatorStack.Count > 0 && (tempChar = operatorStack.Pop()) != '(')
                        {
                            result.Enqueue(tempChar);
                        }
                    }
                    else
                    {
                        tempNum = "" + cur;
                        j = i;
                        while (j < expression.Length && (expression[j] == '.' || (expression[j] >= '0' && expression[j] <= '9')))
                        {
                            tempNum += expression[j++];
                        }
                        i = j;
                        result.Enqueue(tempNum);
                    }
                }
            }
            while (operatorStack.Count > 0)
            {
                cur = operatorStack.Pop();
                if (cur == '#') continue;
                if (operatorStack.Count > 0)
                {
                    top = operatorStack.Peek();
                }

                result.Enqueue(cur);
            }

            return result;
        }

        public double Calucate(string expression)
        {
            try
            {
                var rpn = PreOrderToPostOrder(expression);
                var operandStack = new Stack<double>();
                double left, right;
                object cur;
                while (rpn.Count > 0)
                {
                    cur = rpn.Dequeue();
                    if (cur is char)
                    {
                        right = operandStack.Pop();
                        left = operandStack.Pop();
                        operandStack.Push(Compute(left, right, (char)cur));
                    }
                    else
                    {
                        operandStack.Push(double.Parse(cur.ToString()));
                    }
                }
                return operandStack.Pop();
            }
            catch
            {
                throw new Exception("表达式格式不正确!");
            }
        }
class MainClass
{
       public static void Main (string[] args)
      {
          
            Console.WriteLine((new TCalculator()).Calucate("1+2+3+4").ToString());
            Console.WriteLine((new TCalculator()).Calucate("1+1%3+4").ToString());
            Console.WriteLine((new TCalculator()).Calucate("1+1-3+4").ToString());
            Console.WriteLine((new TCalculator()).Calucate("0").ToString());
            Console.WriteLine((new TCalculator()).Calucate("2-1+3").ToString());
            Console.WriteLine((new TCalculator()).Calucate("2-(1+3)").ToString());
            Console.WriteLine((new TCalculator()).Calucate("11-(15+30)").ToString());
            Console.ReadKey();
        }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
增强型for语句与java,c#的不同之处,with语句的使用发布时间:2022-07-13
下一篇:
C#中DataGridView和ListView闪烁问题的解决方法发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap