表达式求值简便算法

假如你有一个表示表达式的字符串,例如:string s="32.76+4*(37+2/35.6)";
怎么求出它的值?好象有点困难吧,现在可以象这样计算它的值了:
double x=s.ToValue();
函数:ToValue()就是本文要说的一种表达式求值的简便算法.
先大体上介绍一下算法
算法分三个层次,每一层次用一个函数来实现,这三个层次分别是:
一、处理括号
找出优先级最高的括号,调用第二个层次的函数计算*和/运算,再调用第三层次的函数做+和 -运算
二、处理 * 和 /运算
经过第一层次的处理,表达式已无括号,这个层次集中处理表达式中的 * 和 / 运算.
三、处理 + 和 - 运算
经过前二个层的处理,表达式已无括号,无 * 和 /运算,本层专门计算加减法.
最后检查一下最终结果,看是否存在异常.正常就返回结果,这个函数就是前面提到的ToValue()
这个函数作为 string类型的扩展函数提供,使用更便捷.
不多说了,上代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using liudazhen;
namespace ConsoleApplication1
{
    class Program
    {
        /// <summary>
        /// 调用示例,示范表达式求值方法的调用方法.注意别忘记导入名空间:liudazhen;
        /// </summary>
        static void Main(string[] args)
        {
            string s = " 12.456 - ( 3.78 - 5.781*3.73 +2.7 * (-5))/3.78 ";
            try
            {
                double v = s.ToValue();
                Console.WriteLine(v.ToString());
                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }


        }
    }
}
namespace liudazhen
{
    /// <summary>
    /// 包含扩展方法的静态类
    /// </summary>
    public static class ldz
    {
        private static string patternmul = @"N?\d+(\.\d+|\.)?\s*[\*/]\s*N?\d+(\.\d+|\.)?";
        private static string patternadd = @"(\-|N)?\d+(\.\d+|\.)?\s*[\-\+]\s*N?\d+(\.\d+|\.)?";
        private static Regex myregexmul = new Regex(patternmul);
        private static Regex myregexadd = new Regex(patternadd);


        /// <summary>
        /// 对返回的表达式的值进行转换和最后校验.
        /// </summary>
        /// <returns>正常反回 double 值,可能引发异常.</returns>
        public static double ToValue(this string s)
        {
            double x=0;
            if (double.TryParse(calcbracket(s).Replace("N", "-"), out x)) return x;
            throw new Exception("表达式书写有误");
        }


        /// <summary>
        /// 取出运算优先级最高的括号内的表达式,调用求值方法求值.
        /// </summary>
        /// <returns>返回未处理完的可能包括括号的剩余的表达式</returns>
        private static String calcbracket(this string s)
        {
            int n1 = -1, n2 = -1;
            string subs = "",subs2="";
            s.Trim();
            string s2 = s;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == '(')  n1 = i;
                if (s[i] == ')')
                {
                    if (n1 == -1) throw new Exception("右括号不配对");
                    n2 = i;
                    subs=s.Substring(n1, n2 - n1 + 1);
                    subs2 = subs.Substring(1, subs.Length - 2);
                    subs2= calcmul(subs2);
                    subs2 = calcadd(subs2);
                    s2= s.Replace(subs,subs2);
                    return calcbracket(s2);
                }
            }
            if (n2 == -1 && n1 != -1) throw new Exception("左括号不配对");
            subs = calcmul(s);
            subs2 = calcadd(subs);
            return subs2;
        }
        /// <summary>
        /// 取出运算优先级最高的乘法和(或)除法表达式,对其进行求值.
        /// </summary>
        /// <returns>返回未处理完的可能包括乘法和(或)除法的剩余的表达式</returns>
        private static String calcmul(this string s)
        {
            string subs = "",subs2="";
            s.Trim();
            string s2 = s;
            string[] num = null;
            double x1=0,x2 = 0.0,x;
            Match M = myregexmul.Match(s);
            if (M.Success)
            {
                subs = M.Value.Trim();
                subs2 = M.Value.Trim();
                if (subs[0] == '-') subs2 = "N" + subs.Remove(0, 1);
                num = subs2.Split('*', '/');
                double.TryParse((num[0].Replace("N", "-")), out x1);
                double.TryParse((num[1].Replace("N", "-")), out x2);
                if (subs2.Contains('*')) x = x1 * x2;
                else
                {
                    if (x2==0) throw (new Exception("除数为零"));
                    x = x1 / x2;
                }
                s2 = s.Replace(subs, x < 0 ? "N" + (-x).ToString() : x.ToString());
                return calcmul(s2);
            }
            else if (s2[0] == '-') s2 = "N" + s2.Remove(0, 1);
            return s2.Trim();
        }


        /// <summary>
        /// 取出运算优先级最高的加法和(或)减法表达式,对其进行求值.
        /// </summary>
        /// <returns>返回未处理完的可能包括加法和(或)减法的剩余的表达式</returns>
        private static String calcadd(this string s)
        {
            string subs = "",subs2="";
            s.Trim();
            string s2 = s;
            string[] num = null;
            double x1 = 0, x2 = 0.0, x;
            Match M = myregexadd.Match(s);
            if (M.Success)
            {
                subs = M.Value.Trim();
                subs2 = M.Value.Trim();
                if (subs[0] == '-') subs2 = "N" + subs.Remove(0, 1);
                num = subs2.Split('+', '-');
                double.TryParse((num[0].Replace("N", "-")), out x1);
                double.TryParse((num[1].Replace("N", "-")), out x2);
                if (subs2.Contains('+'))
                    x = x1 + x2;
                else
                    x = x1 - x2;
                s2 = s.Replace(subs, x < 0 ? "N" + (-x).ToString() : x.ToString());
                return calcadd(s2);
            }
            else if (s2[0] == '-') s2 = "N" + s2.Remove(0, 1);
            return s2.Trim();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值