Пример #1
0
        /// <summary>
        /// 计算后缀表达式
        /// </summary>
        /// <param name="value">后缀表达式</param>
        /// <returns></returns>
        public static Object Calculate(Stack <Object> value)
        {
            Stack <Object> post = new Stack <Object>();

            while (value.Count > 0)
            {
                post.Push(value.Pop());
            }
            Stack <Object> stack = new Stack <Object>();

            while (post.Count > 0)
            {
                Object obj = post.Pop();
                if (obj != null && obj.GetType().FullName == "JinianNet.JNTemplate.Operator")
                {
                    Object y = stack.Pop();
                    Object x = stack.Pop();
                    stack.Push(Calculate(x, y, OperatorHelpers.ToString((Operator)obj)));
                }
                else
                {
                    stack.Push(obj);
                }
            }

            return(stack.Pop());
        }
Пример #2
0
        /// <summary>
        /// 处理表达式
        /// </summary>
        /// <param name="value">表达式</param>
        /// <returns></returns>
        public static Stack <Object> ProcessExpression(String value)
        {
            value = value.Replace("  ", String.Empty);
            List <Object> result = new List <Object>();
            Int32         j      = 0;
            Int32         i;
            String        num;

            for (i = 0; i < value.Length; i++)
            {
                switch (value[i])
                {
                case '+':
                case '-':
                case '*':
                case '/':
                case '(':
                case ')':
                case '%':
                    if (j < i)
                    {
                        num = value.Substring(j, i - j);
                        if (num.IndexOf('.') == -1)
                        {
                            result.Add(Int32.Parse(value.Substring(j, i - j)));
                        }
                        else
                        {
                            result.Add(Double.Parse(value.Substring(j, i - j)));
                        }
                        j = i;
                    }
                    result.Add(OperatorHelpers.Parse(value[i].ToString()));
                    j++;
                    break;
                }
            }
            if (j < i)
            {
                result.Add(Double.Parse(value.Substring(j, i - j)));
            }
            return(ProcessExpression(result.ToArray()));
        }