WEB开发网
开发学院软件开发C语言 用 C# 设计与实现一个算术运算解释器 2 阅读

用 C# 设计与实现一个算术运算解释器 2

 2009-05-28 08:28:55 来源:WEB开发网   
核心提示: OpTokentoken1=(OpToken)root.Token;switch(token1.Arity){caseOpArity.Binary:if(root.RightChild==null||root.LeftChild==null){thrownewParseFailureExc

OpToken token1 = (OpToken)root.Token;
 
switch (token1.Arity) {
 
  case OpArity.Binary:
 
    if (root.RightChild == null || root.LeftChild == null) {
      throw new ParseFailureException(
        "The expression '{0}' cannot be a value.",
        root.Token.ToString()
      );
    } else {
 
      double lvalue = this.Eval(root.LeftChild);
      double rvalue = this.Eval(root.RightChild);
 
      switch (token1.Value) {
 
        case OpName.Addition:
          return lvalue + rvalue;
 
        case OpName.Subtraction:
          return lvalue - rvalue;
 
        case OpName.Multiplication:
          return lvalue * rvalue;
 
        case OpName.Division:
          return lvalue / rvalue;
 
        case OpName.Exponential:
          return Math.Pow(lvalue, rvalue);
 
        case OpName.Modulus:
          return (int)lvalue % (int)rvalue;
 
        default:
          throw new ParseFailureException(
            "The expression '{0} {1} {2}' cannot be a value.",
            root.LeftChild,
            root.Token,
            root.RightChild
          );
      }
 
    }
 
  case OpArity.Unary:
 
    if (root.RightChild == null) {
 
      throw new ParseFailureException(
        "The expression '{0}' cannot be a value.",
        root.Token.ToString()
      );
 
    } else {
 
      double rvalue = this.Eval(root.RightChild);
 
      switch (token1.Value) {
 
        case OpName.NegativeSign:
          return -rvalue;
 
        case OpName.PositiveSign:
          return rvalue;
 
        default:
          throw new ParseFailureException(
            "The expression '{0} {1}' cannot be a value.",
            root.Token,
            root.RightChild
          );
      }
    }
}

上一页  1 2 3 4 5 6  下一页

Tags:设计 实现 一个

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接