2014-07-04 70 views
-2

我正在編寫一個讀取中綴表示法的程序,將其轉換爲Postfix,然後評估該Postfix。這是我的程序:將Infix轉換爲Postfix並評估Postfix表示法

#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]); 
} 

該程序正確地將我的Infix轉換爲Postfix符號。但是,對於評估部分,結果總是返回0。

此外,當從Infix轉換到Postfix時,我想在每一步打印結果,我該怎麼做?

+0

小注:有趣的名字:'pushit'。它確實p.u. – chux

+1

注意:如果您的條目包含空格,則'scanf(「%s」,infx);'不會掃描整行。 – chux

+0

代碼太多,調試太少。 –

回答

0

的一個問題是您在s爲每件1個字節的存儲一個char存儲的值,然後試圖推整數爲s有:

pushit (int ele) {  /* Function for PUSH operation */ 
    s[++top] = ele; 
} 

s混合INT /炭後,您嘗試讀:

op2=popit(); 
op1=popit(); 

它試圖創建一個popit()intpopit()只是一個1字節的char。所以op1op2沒有得到你想要的值:您需要看一下,如果你希望得到整數回你是如何存儲整數

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’ 

這可能是你的意圖。但是,您的代碼應該在沒有警告的情況下構建,以幫助確保它正在執行您認爲正在執行的操作。

+0

是的,你是對的!非常感謝你的幫助!我終於開始工作了! – user3096716

-2

In line no。 9 類型:

char push(char elem) 

&線沒有。 32 類型:

int pushit(int ele)