主页 > 编程资料 > C# >
发布时间:2015-09-26 作者:网络 阅读:267次

这是一个实现四则混合运算的代码,包括三个方法,调用时,使用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)");
 
           oArr.Push("#");
           w = Convert.ToString(arr[j++]);
           while(!(w == "#" && Convert.ToString(oArr.Peek()) == "#"))
           {
              if("+-*/()#".IndexOf(w) != -1)
              {
                  switch(Precede(oArr.Peek().ToString(), w))
                  {
                     case "<":
                         oArr.Push(w);
                         w = Convert.ToString(arr[j++]);
                         break;
                     case "=":
                         oArr.Pop();
                         w = Convert.ToString(arr[j++]);
                         break;
                     case ">":
                         o = Convert.ToChar(oArr.Pop());
                         b = Convert.ToDouble(nArr.Pop());
                         a = Convert.ToDouble(nArr.Pop());
                         nArr.Push(Operate(a, o, b));
                         break;
                     default:
                         return "计算出错!";   
                  }
              }
              else
               {
                  nArr.Push(w);
                  w = Convert.ToString(arr[j++]);
              }
           }
           return nArr.Pop();
       }


 

<> <>
关键字词: