C 中缀到后缀的转换和后缀符号的求值
我正在编写一个程序,读取中缀符号,将其转换为后缀,然后计算该后缀。以下是我的节目:C 中缀到后缀的转换和后缀符号的求值,c,stack,postfix-notation,infix-notation,C,Stack,Postfix Notation,Infix Notation,我正在编写一个程序,读取中缀符号,将其转换为后缀,然后计算该后缀。以下是我的节目: #include<stdio.h> #include <ctype.h> #define SIZE 50 /* Size of Stack */ char s[SIZE]; int top = -1; /* Global declarations */ push(char elem) { /* Function for PUSH operation */ s[
#include<stdio.h>
#include <ctype.h>
#define SIZE 50 /* Size of Stack */
char s[SIZE];
int top = -1; /* Global declarations */
push(char elem) { /* Function for PUSH operation */
s[++top] = elem;
}
char pop() { /* Function for POP operation */
return (s[top--]);
}
int pr(char elem) { /* Function for precedence */
switch (elem) {
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}
pushit(int ele){ /* Function for PUSH operation */
s[++top]=ele;
}
int popit(){ /* Function for POP operation */
return(s[top--]);
}
main() { /* Main Program */
char infx[50], pofx[50], ch, elem;
int i = 0, k = 0, op1, op2,ele;
printf("\n\nRead the Infix Expression ");
scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != '\0') {
if (ch == '(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
} else { /* Operator */
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
while( (ch=pofx[i++]) != '\0')
{
if(isdigit(ch)) pushit(ch-'0'); /* Push the operand */
else
{ /* Operator,pop two operands */
op2=popit();
op1=popit();
switch(ch)
{
case '+':pushit(op1+op2);break;
case '-':pushit(op1-op2);break;
case '*':pushit(op1*op2);break;
case '/':pushit(op1/op2);break;
}
}
}
printf("\n Given Postfix Expn: %s\n",pofx);
printf("\n Result after Evaluation: %d\n",s[top]);
}
程序将我的中缀正确地转换为后缀符号。但是,对于求值部分,其结果总是返回0
此外,当从中缀转换为后缀时,我想在每个步骤中打印结果,我如何才能做到这一点?一个问题是,您将值存储在s中,作为字符,每个元素的存储空间为1字节,然后尝试将整数推入s中,并使用: 在s中混合int/char后,尝试读取:
op2=popit();
op1=popit();
它尝试从popit创建int。popit只是一个1字节的字符。所以op1和op2没有得到您想要的值:
int popit(){ /* Function for POP operation */
return(s[top--]);
}
如果希望返回整数,则需要查看存储整数的方式。最后,看看你的警告。至少,使用-Wall选项构建。它揭示了:
popit.c:8:1: warning: return type defaults to ‘int’
popit.c:32:1: warning: return type defaults to ‘int’
popit.c:41:1: warning: return type defaults to ‘int’
这可能是你想要的。但是,您的代码应该在没有警告的情况下构建,以帮助确保它正在做您认为它正在做的事情。第9行
类型:
&第32行
类型:
小调:有趣的名字:pushit。注意:如果您的条目包含空格,则扫描%s,infx;不会扫描整行。代码太多,调试太少。@chux哈哈哈。。。你指出的时候我才注意到。不用担心,我更改了函数的名称!是的,你说得对!!非常感谢你的帮助!我终于成功了!
popit.c:8:1: warning: return type defaults to ‘int’
popit.c:32:1: warning: return type defaults to ‘int’
popit.c:41:1: warning: return type defaults to ‘int’
char push(char elem)
int pushit(int ele)