PDA

View Full Version : محاسبه عبارت پسوندی



GENERAL IRAJ
دوشنبه 02 دی 1392, 23:17 عصر
برنامه ای نوشتیم که عبارت میانوندی را گرفته و به پسوندی تبدیل می کند.
ولی نمی دونم که چه طوری محاسبه کنم لطفاً کمکم کنید:

#include <iostream>
#include <conio>
#include <stdlib>
#define MAX 100
char stack[MAX];
int top=-1;
char pop();
void push(char item);
int prcd(char symbol);
bool isoperator(char symbol);
void convert(char infix[],char postfix[]);
int main()
{
char infix[100],postfix[100];
cout << "please Enter your INFIX notation:\n";
cin >> infix;
convert (infix,postfix);
cout <<"the POSTFIX notation is:\n"<<postfix;
getch();
return 0;
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
void push(char i)
{
top++;
stack[top]=i;
}
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 2;
break;
case '*':
case '/':return 4;
break;
case '^':
return 6;
break;
case '(':
case ')':
case '#':return 1;
break;
}
}
bool isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':return 1;
break;
default:return 0;
}
}
void convert(char infix[],char postfix[])
{
int i,j=0;
char symbol,symbol2;
stack[++top]='#';
int n=strlen(infix);
for(i=0;i<n;i++)
{
symbol=infix[i];
if(!isoperator(symbol))
{ int x=i;
while(!isoperator(infix[x]))
{
postfix[j]=infix[x];
j++;
x++;
i=x;
}
postfix [j] = ' ';
i=x-1;

}
else{
if(symbol=='(')push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
postfix[j]=' ';
}
pop();
}
else{
if(prcd(symbol)>prcd(stack[top]))
push(symbol);
else{
while(prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
postfix[j]=' ';
}
push(symbol);
}
}
}
}
while(stack[top]!='#')
{
postfix[j]=pop();
j++;
postfix[j]=' ';
}
postfix[j]='\0';//null terminate string.
}