0
我有以下代碼來評估我的表達式樹。但問題是它給了我錯誤的答案。我已經測試過,並發現當我的代碼評估表達式樹
double left = (double) Character.digit((char) evaluateTree(t.left),
10);
左值等於-1,我相信'+'的雙倍值。當我調用root.left(它是'+')並嘗試使用Character.digit(char)來獲得它的double值時,它會給我-1。由於我的樹就像是:
//My infix : (2+5)*7 MyPostfix : 25+7*
*
/\
+ 7
/\
2 5
評估方法:
public double evaluateTree(TreeNode t) {
if(root == null)
return 0;
if (Character.isDigit(t.ch))
return (double)t.ch;
else {
char c = t.ch;
double left = (double) Character.digit((char) evaluateTree(t.left),
10);
double right = (double) Character.digit(
(char) evaluateTree(t.right), 10);
//checks what to do for operators for example for '+' return left+right
return evaluate(c, left, right);
}
}
當前結果= -7.0
我該如何解決這個問題?
public double evaluate(char c, double left, double right) {
double result = 0;
switch (c) {
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
result = left/right;
break;
case '%':
result = left % right;
break;
}
return result;
}
'evaluate()?' – EJP 2015-03-25 00:07:31
@EJP添加評估。 – Kaan 2015-03-25 00:30:11