コード例 #1
0
        /// <summary>
        /// Evaluating reverse polish notation
        /// </summary>
        /// <param name="value">The reverse polish notation.</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, OperatorConvert.ToString((Operator)obj)));
                }
                else
                {
                    stack.Push(obj);
                }
            }

            return(stack.Pop());
        }
コード例 #2
0
        /// <summary>
        /// process expression.
        /// </summary>
        /// <param name="value">The expression.</param>
        /// <returns></returns>
        public static Stack <object> ProcessExpression(string value)
        {
            value = value.Replace("  ", string.Empty);
            List <object> result = new List <object>();
            int           j      = 0;
            int           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(int.Parse(value.Substring(j, i - j)));
                        }
                        else
                        {
                            result.Add(Double.Parse(value.Substring(j, i - j)));
                        }
                        j = i;
                    }
                    result.Add(OperatorConvert.Parse(value[i].ToString()));
                    j++;
                    break;
                }
            }
            if (j < i)
            {
                result.Add(Double.Parse(value.Substring(j, i - j)));
            }
            return(ProcessExpression(result.ToArray()));
        }