计算器程序使用堆栈

时间:2015-10-24 02:58:41

标签: c stack infix-notation postfix-operator

我正在使用堆栈在c中编写计算器程序。在下面的程序中,我使用了中缀的概念来进行后缀转换和下一个后缀评估。 我得到正确答案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 个答案:

答案 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);
}
}