我制作了一个C程序来评估后缀表达式。输出错误。我在各个地方添加了打印消息,以查看Iam出了什么问题。在for循环主体的第4行或第5行出现。我不明白为什么会这样。

 #include <stdio.h>
 #include <string.h>

  char exp[20];
 int stck[15];
 int tos = -1;

 int isEmpty() {
   if (tos == -1)
     return 1;
   return 0;
 }

 int isFull() {
   if (tos == 9)
     return 1;
   return 0;
 }

 int pop() {
   if (!(isEmpty()))
     return stck[tos--];
   else
     printf("Underflow\n");
 }

 void push(int c) {
   if (!(isFull()))
     stck[++tos] = c;
   else
     printf("Overflow\n");
 }

 int isOperator(char c) {
   if (c == '+' || c == '-' || c == '/' || c == '%' || c == '*')
     return 1;
   return 0;
 }

 main() {
   int i, a, b, c;
   printf("Enter the expression\n");
   gets(exp);
   for (i = 0; exp[i] != '\0'; i++) {
     printf("Current symbol is %c\n", exp[i]);
     if (!(isOperator(exp[i]))) {
       push((int) exp[i]);
       printf("Pushed %d into the stack\n", stck[tos]);
     } else {
       b = pop();
       a = pop();
       printf("Value of a and b are : %d and %d \n", a, b);
       if (exp[i] == '+')
         c = a + b;
       if (exp[i] == '-')
         c = a - b;
       if (exp[i] == '*')
         c = a * b;
       if (exp[i] == '/')
         c = a / b;
       if (exp[i] == '%')
         c = a % b;
       push(c);
       printf("C pushed. top of stack is now %d\n", stck[tos]);
     }
   }
   printf("The value of expression is: %d\n", pop());
 }

最佳答案

这里有一个问题。

push((int) exp[i]);


您正在此处推送ASCII值而不是数字。

你想要的是

   push(exp[i]-'0'); // Converts ASCII to digit.

07-24 09:46