2015-10-24 80 views
2

我正在用c语言编写一个计算器程序,在下面的程序中,我使用了中缀的概念来转换后缀和下一次postfix评估。 我得到正确的答案1 + 2答案是3但11 + 1或任何两个和更多的数字我得到错误的答案。计算器程序使用堆栈

任何人都可以帮助我,我将包括在我的代码,以便它可以工作在两个以上的数字,如28 + 25或任何?我自己的代码

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 
#define SIZE 50   /* Size of Stack */ 

int top = -1; 
char pofx[50]; 
char s[SIZE]; 
int infix_to_postfix() { 

    char infx[50], ch; 
    int i = 0, k = 0; 

    void 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; 
    } 
    return -1; 
    } 
    printf("\n\nEnter a Value to calculate : "); 
    gets(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(); 
     char 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); 

    return (int) pofx[k]; 
} 

void postfix_evaluate() { 

    char ch; 
    int i = 0, op1, op2; 
    void pushit(int elem) { /* Function for PUSH operation */ 
    s[++top] = elem; 
    } 

    int popit() { /* Function for POP operation */ 
    return (s[top--]); 
    } 
    infix_to_postfix(); 
    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]); 
} 

int main() { 
    postfix_evaluate(); 
    return 0; 
} 
+1

,我可以看到你在呼唤“POPIT()”来获得数字和“POPIT()”返回字符从“SIZE”开始,所以即使你输入了两位数字,你也会得到一个数字。我想这就是为什么这只适用于一个数字。 – Deshan

+0

注意:在函数内部定义函数是一个gcc扩展,并且你有两个相同的(除了它们的名字)push/pop函数。如何让他们脱离功能并定义一对push/pop? – MikeCAT

+0

我试着只定义一个函数,但结果总是为0。 –

回答

0

部分可能有用:

if (isdigit(gi.n.nch)) 
{ 
gi.x = chr2num(gi.n.nch); 
gi.n= nextchar(gi.n, len, instr); 
while(isdigit(gi.n.nch)) 
{ 
    gi.x *= 10; 
    gi.x += chr2num(gi.n.nch); 
    gi.n= nextchar(gi.n, len, instr); 
} 
}