public double Visit(BinaryExpr bin) { if (bin.OP == OPERATOR.PLUS) { return(bin.Left.accept(this) + bin.Right.accept(this)); } else if (bin.OP == OPERATOR.MUL) { return(bin.Left.accept(this) * bin.Right.accept(this)); } else if (bin.OP == OPERATOR.DIV) { return(bin.Left.accept(this) / bin.Right.accept(this)); } else if (bin.OP == OPERATOR.MINUS) { return(bin.Left.accept(this) - bin.Right.accept(this)); } return(Double.NaN); }
static void Main(string[] args) { Expr r = new BinaryExpr(new Number(2), new BinaryExpr(new Number(3), new Number(4), OPERATOR.MUL), OPERATOR.PLUS); double n = r.accept(new TreeEvaluatorVisitor()); Console.WriteLine(n); r.accept(new ReversePolishEvaluator()); Console.WriteLine(); StackEvaluator s = new StackEvaluator(); r.accept(s); Console.WriteLine(s.get_value()); Console.WriteLine(); r = new BinaryExpr( new UnaryExpr(new Number(10), OPERATOR.MINUS), new Number(15), OPERATOR.PLUS); s = new StackEvaluator(); r.accept(s); Console.WriteLine(s.get_value()); r.accept(new ReversePolishEvaluator()); Console.Read(); }
public double Visit(BinaryExpr bin) { bin.Left.accept(this); bin.Right.accept(this); if (bin.OP == OPERATOR.PLUS) { eval_stack.Push(eval_stack.Pop() + eval_stack.Pop()); } else if (bin.OP == OPERATOR.MUL) { eval_stack.Push(eval_stack.Pop() * eval_stack.Pop()); } else if (bin.OP == OPERATOR.DIV) { eval_stack.Push(eval_stack.Pop() / eval_stack.Pop()); } else if (bin.OP == OPERATOR.MINUS) { eval_stack.Push(eval_stack.Pop() - eval_stack.Pop()); } return(Double.NaN); }
public double Visit(BinaryExpr bin) { bin.Left.accept(this); bin.Right.accept(this); if (bin.OP == OPERATOR.PLUS) { Console.Write(" + "); } else if (bin.OP == OPERATOR.MUL) { Console.Write(" * "); } else if (bin.OP == OPERATOR.DIV) { Console.Write(" / "); } else if (bin.OP == OPERATOR.MINUS) { Console.Write(" - "); } return(Double.NaN); }