无法找出我的代码中的逻辑错误

时间:2015-08-07 03:32:46

标签: c string infix-notation

我的代码中存在一些逻辑错误,但我无法弄清楚它是什么。当我运行我的代码时,它不会给我想要的结果。

输出:

Enter an infix expression
2+3
2

我得到2作为我的后缀表达式,而我应该得到23+。 请看看是否有人可以帮我解决这个问题。

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#define max 20
int top=-1;
char infix[max],postfix[max],stack[max];
char pop();
int empty();
void push(char );
int precedence(char );
void infix_to_postfix(char * ,char * );

void main()
{
clrscr();
printf("Enter an infix expression\n");
gets(infix);
infix_to_postfix(infix,postfix);
printf("%s",postfix);
getch();
}

void infix_to_postfix(char infix[max],char postfix[max])
{
int i=0,j=0;
char value,x;
for(i=0;infix[i]!='\0';i++)
{
value=infix[i];
if(isalnum(value))
{
postfix[j]=value;
j++;
}
else
{
if(value=='(')
push('(');
else
{
if(value==')')
{
while((x=pop())!='(')
{
postfix[j]=x;
j++;
}
}
else
{
while(precedence(value)<=precedence(stack[top])&&!empty())
{
x=pop();
postfix[j]=x;
j++;
}
push(value);
}
}
}
}

while(!empty())
{
x=pop();
postfix[j]=x;
j++;
}
postfix[j]='\0';
}

void push(char x)
{
if(top==max-1)
printf("stack overflow\n");
else
{
top++;
stack[top]=x;
}
}

char pop()
{
char x;
x=stack[top];
top--;
return x;
}

int empty()
{
if(top==-1)
return(0);
return(1);
}

int precedence(char value)
{
if(value=='(')
return(0);
if(value=='+'||value=='-')
return(1);
if(value=='*'||value=='/'||value=='%')
return(2);
return(3);
}

2 个答案:

答案 0 :(得分:0)

您需要做的就是更改empty()功能  你在if条件下检查!empty(),但是你返回0,当它为空时,这将使条件为真,即Stack不为空。如果是空堆栈,则将返回值更改为1.

答案 1 :(得分:0)

通常,代码的逻辑是正常的,除了empty()函数中的返回值错误 在empty()中,当堆栈为空时,它应返回1。

  int empty(){
     if(top==-1)
        return(0);  <-- !!! here should return 1
     }  

否则,

  1. 即使堆栈为空,它也会进入while(precedence(value)<=precedence(stack[top])&&!empty())的while循环。
  2. 然后postfix[j] = x可能会将冗余0(现在顶部= -2)写入postfix数组。
  3. 最后,在输入2+3下,postfix[]将为{'2','\0','3','+',...},这会导致输出异常2
  4. 因此,在修改empty()函数后,它将起作用,例如

    int empty()
    {
        if(top==-1)
           return(1); // not return(0)
        return(0); 
    }
    

    输出:

    Enter an infix expression
    2+3
    23+
    
相关问题