日期:2011-07-07  浏览次数:20460 次

这是一个实现四则混合运算的代码,包括三个方法,调用时,使用Compute()方法即可,这个方法可以用于动态计算。
 
代码:
         string Precede(string p, string q)
       {
           switch(p)
           {
              case "+":
              case "-":
                  return ("*/(".IndexOf(q) != -1) ? "<":">";
              case "*":
              case "/":
                  return (q == "(") ? "<":">";
              case "(":
                  return (q == ")") ? "=":"<";
              case ")":
                  return (q == "(") ? "?":">";
              case "#":
                  return (q == "#") ? "=":"<";
           }
           return "?";
       }
 
       double Operate(double a, char o, double b)
       {
           switch(o)
           {
              case '+':
                  return a + b;
              case '-':
                  return a - b;
              case '*':
                  return a * b;
              case '/':
                  return a / b;
           }
           return 0;
       }
 
       object Compute(string expression)
       {
           Stack nArr = new Stack(), oArr = new Stack();
           int j = 0;
           Double a = 0, b = 0;
           string w = "";
           char o;
           MatchCollection arr = Regex.Matches(expression.Replace(" ", "") + "#", @"(((?<=(^|\())-)?\d+(\.\d+)?|\D)");
&nbs