一种表达式求值的简便算法

假如你有一个表示表达式的字符串,例如:string s="32.76+4*(37+2/35.6)";

怎么求出它的值?好象有点困难吧,现在可以象这样计算它的值了:

double x=s.ToValue();

函数:ToValue()就是本文要说的一种表达式求值的简便算法.

先大体上介绍一下算法

算法分三个层次,每一层次用一个函数来实现,这三个层次分别是:

一、处理括号

找出优先级最高的括号,调用第二个层次的函数计算*和/运算,再调用第三层次的函数做+和 -运算

二、处理 * 和 /运算

经过第一层次的处理,表达式已无括号,这个层次集中处理表达式中的 * 和 / 运算.

三、处理 + 和 - 运算

经过前二个层的处理,表达式已无括号,无 * 和 /运算,本层专门计算加减法.

最后检查一下最终结果,看是否存在异常.正常就返回结果,这个函数就是前面提到的ToValue()

这个函数作为 string类型的扩展函数提供,使用更便捷.

不多说了,上代码:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Text.RegularExpressions;
  6 using liudazhen;
  7 
  8 namespace ConsoleApplication1
  9 {
 10     class Program
 11     {
 12         /// <summary>
 13         /// 调用示例,示范表达式求值方法的调用方法.注意别忘记导入名空间:liudazhen;
 14         /// </summary>
 15         static void Main(string[] args)
 16         {
 17             string s = " 12.456 - ( 3.78 - 5.781*3.73 +2.7 * (-5))/3.78 ";
 18             try
 19             {
 20                 double v = s.ToValue();
 21                 Console.WriteLine(v.ToString());
 22                 Console.ReadKey();
 23             }
 24             catch (Exception e)
 25             {
 26                 Console.WriteLine(e.Message);
 27                 Console.ReadKey();
 28             }
 29 
 30         }
 31     }
 32 }
 33 namespace liudazhen
 34 {
 35     /// <summary>
 36     /// 包含扩展方法的静态类
 37     /// </summary>
 38     public static class ldz
 39     {
 40         private static string patternmul = @"N?\d+(\.\d+|\.)?\s*[\*/]\s*N?\d+(\.\d+|\.)?";
 41         private static string patternadd = @"(\-|N)?\d+(\.\d+|\.)?\s*[\-\+]\s*N?\d+(\.\d+|\.)?";
 42         private static Regex myregexmul = new Regex(patternmul);
 43         private static Regex myregexadd = new Regex(patternadd);
 44 
 45         /// <summary>
 46         /// 对返回的表达式的值进行转换和最后校验.
 47         /// </summary>
 48         /// <returns>正常反回 double 值,可能引发异常.</returns>
 49         public static double ToValue(this string s)
 50         {
 51             double x=0;
 52             if (double.TryParse(calcbracket(s).Replace("N", "-"), out x)) return x;
 53             throw new Exception("表达式书写有误");
 54         }
 55 
 56         /// <summary>
 57         /// 取出运算优先级最高的括号内的表达式,调用求值方法求值.
 58         /// </summary>
 59         /// <returns>返回未处理完的可能包括括号的剩余的表达式</returns>
 60         private static String calcbracket(this string s)
 61         {
 62             int n1 = -1, n2 = -1;
 63             string subs = "",subs2="";
 64             s.Trim();
 65             string s2 = s;
 66             for (int i = 0; i < s.Length; i++)
 67             {
 68                 if (s[i] == '(')  n1 = i;
 69                 if (s[i] == ')')
 70                 {
 71                     if (n1 == -1) throw new Exception("右括号不配对");
 72                     n2 = i;
 73                     subs=s.Substring(n1, n2 - n1 + 1);
 74                     subs2 = subs.Substring(1, subs.Length - 2);
 75                     subs2= calcmul(subs2);
 76                     subs2 = calcadd(subs2);
 77                     s2= s.Replace(subs,subs2);
 78                     return calcbracket(s2);
 79                 }
 80             }
 81             if (n2 == -1 && n1 != -1) throw new Exception("左括号不配对");
 82             subs = calcmul(s);
 83             subs2 = calcadd(subs);
 84             return subs2;
 85         }
 86         /// <summary>
 87         /// 取出运算优先级最高的乘法和(或)除法表达式,对其进行求值.
 88         /// </summary>
 89         /// <returns>返回未处理完的可能包括乘法和(或)除法的剩余的表达式</returns>
 90         private static String calcmul(this string s)
 91         {
 92             string subs = "",subs2="";
 93             s.Trim();
 94             string s2 = s;
 95             string[] num = null;
 96             double x1=0,x2 = 0.0,x;
 97             Match M = myregexmul.Match(s);
 98             if (M.Success)
 99             {
100                 subs = M.Value.Trim();
101                 subs2 = M.Value.Trim();
102                 if (subs[0] == '-') subs2 = "N" + subs.Remove(0, 1);
103                 num = subs2.Split('*', '/');
104                 double.TryParse((num[0].Replace("N", "-")), out x1);
105                 double.TryParse((num[1].Replace("N", "-")), out x2);
106                 if (subs2.Contains('*')) x = x1 * x2;
107                 else
108                 {
109                     if (x2==0) throw (new Exception("除数为零"));
110                     x = x1 / x2;
111                 }
112                 s2 = s.Replace(subs, x < 0 ? "N" + (-x).ToString() : x.ToString());
113                 return calcmul(s2);
114             }
115             else if (s2[0] == '-') s2 = "N" + s2.Remove(0, 1);
116             return s2.Trim();
117         }
118 
119         /// <summary>
120         /// 取出运算优先级最高的加法和(或)减法表达式,对其进行求值.
121         /// </summary>
122         /// <returns>返回未处理完的可能包括加法和(或)减法的剩余的表达式</returns>
123         private static String calcadd(this string s)
124         {
125             string subs = "",subs2="";
126             s.Trim();
127             string s2 = s;
128             string[] num = null;
129             double x1 = 0, x2 = 0.0, x;
130             Match M = myregexadd.Match(s);
131             if (M.Success)
132             {
133                 subs = M.Value.Trim();
134                 subs2 = M.Value.Trim();
135                 if (subs[0] == '-') subs2 = "N" + subs.Remove(0, 1);
136                 num = subs2.Split('+', '-');
137                 double.TryParse((num[0].Replace("N", "-")), out x1);
138                 double.TryParse((num[1].Replace("N", "-")), out x2);
139                 if (subs2.Contains('+'))
140                     x = x1 + x2;
141                 else
142                     x = x1 - x2;
143                 s2 = s.Replace(subs, x < 0 ? "N" + (-x).ToString() : x.ToString());
144                 return calcadd(s2);
145             }
146             else if (s2[0] == '-') s2 = "N" + s2.Remove(0, 1);
147             return s2.Trim();
148         }
149     }
150 }

 

 

posted @ 2012-05-19 10:44  liudz  阅读(519)  评论(3)    收藏  举报