用 C# 设计与实现一个算术运算解释器 2
2009-05-28 08:28:55 来源:WEB开发网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
);
}
}
}
更多精彩
赞助商链接