#include <stdio.h>
#include <ctype.h>
char stack[50];
int top=-1;
void push(char x)
{
stack[++top]=x;
}
char pop()
{
if(top==-1)
return -1;
else
return stack[top--];
}
此函数用于对运算符进行优先级排序:
int priority(char x)
{
if(x=='+'|| x=='-') {
return 1;
} else if(x=='(') {
return 0;
} else if(x=='*'||x=='/') {
return 2;
} else {
return 3;
}
}
int main()
{
char exp[50], *e, x;
scanf("%s", exp);
e = exp;
while(*e != '\0') {
if(isalnum(*e)) {
printf("%c",*e);
} else {
while(priority(stack[top]) >= priority(*e)) {
printf("%c",pop());
}
push(*e);
}
e++;
}
while(top!=-1) {
printf("%c",pop());
}
return 0;
}
我在此程序中遇到运行时错误。我不知道为什么。您能建议我进行任何更改吗?在某些编译器中,我将输出作为无限循环。
最佳答案
第一次执行此代码
while(priority(stack[top])>=priority(*e))
top
的值是-1
,因此您可以访问stack[-1]
。那不是合法的访问,您的程序可能会崩溃。如果程序没有崩溃,您将获得传递给
priority
的一些“随机”值。现在,您将此“随机”字符的优先级与输入的第一个字符的优先级进行比较。假设比较结果为true。然后执行:printf("%c",pop());
由于
top
是-1
,因此pop
功能不会更改top
,因此它将保持在-1
。然后,您再次执行以下操作:while(priority(stack[top])>=priority(*e))
由于
top
和*e
均未更改,因此比较将再次为true。换句话说-无限循环。关于c - 这个在C中将中缀转换为后缀的程序给出了运行时错误。为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43178278/