我正在尝试使用堆栈实现后缀求值,但计算后的结果不正确,我不知道是哪个部分使计算出错,非常感谢。
import java.util.Stack;
public class PostFixEvaluate {
public static float calculate(Float operand_1,char operator,Float operand_2 ){
switch(operator){
case '+':
return operand_2 + operand_1;
case '-':
return operand_2 - operand_1;
case '*':
return operand_2 * operand_1;
case '/':
return operand_2 / operand_1;
}
return 0;
} //end calculate()
public static float postFixEvaluation(String expr){
Stack<Float> stack = new Stack<>();
int index = 0;
while(index < expr.length()){
char token = expr.charAt(index);
boolean x = isOperand(token);
if(x == true){ //operand
float operandIn = (float)token;
stack.push(operandIn);
}
else{ //operator
float a = stack.pop(); //operand_1
float b = stack.pop(); //operand_2
char w = token; //operator
stack.push(calculate(a, w, b));
}
index += 1;
} //end while
float result = stack.pop();
return result;
} //postFixEvaluation()
/*Operand or operator? operator return 1, operand return 2*/
public static boolean isOperand(char c){
switch(c){
case '+':
case '-':
case '*':
case '/':
return false; //an operator
default:
return true; //an operand
} //end switch()
} //end isOperand()
}
输入后缀"312*+456*+97-/+"后,结果是3958.0,预期是22.0,这比错误多了,但我仍然不明白为什么结果是3958.0。
char token = expr.charAt(index);
在第一次迭代时返回'3'
,但这是一个代表字符'3'
(即51)的char
,而不是数字3。
要使用该数字而不是表示该数字的字符,可以通过从其中减去'0'
将其推入堆栈,如下所示:
stack.push(operandIn - '0');