我一直在制作一个程序,借助堆栈将中缀输入转换为后缀。
我编写的程序如下
这作为无限循环运行,不打印任何相关内容。我一直试图找到错误但没有成功,编译器也没有发出任何警告。
#include<stdio.h>
char po[20];
int top = -1;
void push(char x) {
po[++top] = x;
}
char pop() {
if (top == -1)
return -1;
else
return po[top--];
}
int priority(char x) {
if (x == '(')
return 0;
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/')
return 2;
}
main() {
char st[20], x;
int a, c = 0, op;
printf("Enter the expression ");
scanf("%s", st);
while (st[c] != '\0') {
if (st[c] >= 'a' && st[c] <= 'z')
printf("%c", st[c]);
else if (st[c] == '(')
push(st[c]);
else if (st[c] == ')')
;
{
while ((x = pop()) != '(')
printf("%c", pop());
}
if (st[c] == '*' || st[c] == '/' || st[c] == '+' || st[c] == '-'
|| st[c] == '^') {
while (priority(po[top]) >= priority(st[c]))
printf("%c", pop());
push(st[c]);
}
c = c + 1
}
while (top != -1) {
printf("%c", pop());
}
}
最佳答案
The compiler also did not issue any warnings.
节省时间。启用所有警告或获取更好的编译器。
warning: control reaches end of non-void function [-Wreturn-type]
查看下面的函数,发现它没有为所有可能的 x
返回值。
int priority(char x) {
if (x == '(')
return 0;
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/')
return 2;
// Missing return
}
<小时/>
warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
下面的代码是可疑的。您真的想要在 else if (st[c] == ')')
之后添加 ;
吗?
else if (st[c] == ')')
;
<小时/>
error: expected ';' before '}' token
肯定是拼写错误(缺少;)
// c = c + 1
c = c + 1;
<小时/>
也可能存在其他问题。
关于c - 中缀到后缀 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54368416/