这是一种使用递归评估算术表达式的算法:
假设:
只有二进制操作
每个操作都有括号(包括最外面的括号)
输入:
代表算术表达式的标记数组
num_tokens是令牌数
令牌示例数组:{“(”,“ 9”,“ +”,“(”,“ 50”,“-”,“ 25”,“)”,“)”}
我尝试实现该算法,但是我的程序无法运行(退出状态-1是我收到的唯一消息)。为什么会这样?
int apply(char op, int a, int b) {
if (op == '+'){
printf("%d %c %d\n", a,op,b);
return a + b;
}
else if (op == '-'){
printf("%d %c %d\n", a,op,b);
return a - b;
}
else if(op == '/'){
printf("%d %c %d\n", a,op,b);
return a / b;
}
else if(op == '*'){
printf("%d %c %d\n", a,op,b);
return a * b;
}
}
int eval_tokens(char** expression, int num_tokens)
{
// implement me
int index;
int opIndex = find_operator(expression, num_tokens); //find index of operator
int count1=0,count2=0,term1,term2,i,j;
if(*expression[0] == '(')
i = 1;
else
i = 0;
while(i <= opIndex){
i++;
count1++;
}
term1 = eval_tokens(expression+1,count1);
j = opIndex+1;
while(j < num_tokens){
count2++;
j++;
}
term2 = eval_tokens(expression+opIndex+1,count2); //expression+opIndex+1 points to index after opIndex
return apply(*expression[opIndex], term1, term2);
}
int main(void) {
char*expression[] = {"(", "(", "5", "+", "3", ")", "-", "(", "2", "+", "1", ")", ")"};
printf("result = %d\n", eval_tokens(expression, 13));
return 0;
}
答案 0 :(得分:1)
要使用str
(或expression
)作为堆栈,您可以从中取出项目,请在递归函数中将这些参数设为“可修改”。因此,您可以引入第二个函数int eval_tokens_recursive(char*** expression, int *num_tokens)
,该函数具有更高的间接级别,并且实际上可以通过更改参数的值来“从堆栈中取出项目”。
代码如下所示。希望对您有所帮助。
int eval_tokens_recursive(char*** expression, int *num_tokens) {
char *token = **expression;
if (*num_tokens == 0) {
printf("expecting more tokens.\n");
exit(1);
}
if (*token == '(') { // begin of expression?
(*expression)++; // skip opening brace
(*num_tokens)--;
// lhs
int lhs = eval_tokens_recursive(expression, num_tokens);
// operand
char operand = ***expression;
(*expression)++;
(*num_tokens)--;
// rhs
int rhs = eval_tokens_recursive(expression, num_tokens);
(*expression)++; // skip closing brace
(*num_tokens)--;
switch (operand) {
case '+':
return lhs + rhs;
case '-':
return lhs - rhs;
case '*':
return lhs * rhs;
case '/':
return lhs / rhs;
default:
return 0;
}
} else { // not an expression; must be a numeric token
int operand;
if (sscanf(token, "%2d", &operand) != 1) {
printf("expecting numeric value; cannot parse %s.\n", token);
exit(1);
}
(*expression)++;
(*num_tokens)--;
return operand;
}
}
int eval_tokens(char** expression, int num_tokens) {
return eval_tokens_recursive(&expression, &num_tokens);
}
int main() {
char *expressions[] = {"(", "9", "+", "(", "50", "-", "25", ")", ")"};
int result = eval_tokens(expressions, 9);
printf("result: %d\n", result);
}