我正在研究基于堆栈的波兰语表示法计算器,该计算器读取一个中缀表达式,验证括号是否正确,将其转换为后缀,然后对其进行最终结果评估。但是我在评估部分遇到了一些问题,代码正在跳过整个“ while”循环(我已经在其中添加了一些printf,以找出它在哪里停止工作),并且始终将最终结果显示为“ 0” '。
这是我的数据结构研究。一切似乎都正常,但评估部分。我尝试添加一些变量,但是没有用。
void postfix(){
int i = 0, op1, op2;
char ch;
int p =-1;
char exp[20];
char *e, x;
e = exp;
printf("Input the expression again: ");
scanf("%s", &exp);
printf("\nThe postfix expression is: ");
while(*e != 0){
if(isalnum(*e)){
printf("%c",*e);
post[++p]=*e;
} else if(*e == '(')
push(*e);
else if(*e == ')'){
while((x = pop()) != '('){
printf("%c", x);
post[++p]=x;
}
} else{
while(priority(pilha[top]) >= priority(*e)){
char a;
a= pop();
printf("%c",a);
post[++p]=a;
}
push(*e);
}
e++;
}
while(top != -1){
char avaliada;
avaliada = pop();
printf("%c",avaliada);
post[++p] = avaliada;
}
}
void evaluation(){
int i = 0, op1, op2;
char ch;
int p =-1;
char exp[20];
char *e, x;
e = exp;
postfix();
while(i != (p+1)){
ch=post[i];
i++;
if(isdigit(ch)){
xpush(ch - '0');
} else{
op2=xpop();
op1=xpop();
switch(ch){
case '+':xpush(op1+op2);break;
case '-':xpush(op1-op2);break;
case '*':xpush(op1*op2);break;
case '/':xpush(op1/op2);break;
}
}
printf("\n\nResult: %d\n",s[xtop]);
}
例如,如果我在控制台中输入“ 2-1”表达式,则希望它显示后缀符号(即“ 21-”)和计算结果(即“ 1”),但是实际输出为“ 0”。