fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <cstring>
  5. #define MAX 50
  6. #define EMPTY -1
  7. struct stack
  8. {
  9. int data[MAX];
  10. int top;
  11. };
  12. void emptystack(struct stack* s)
  13. {
  14. s->top = EMPTY;
  15. }
  16. void push(struct stack* s,int item)
  17. {
  18. if(s->top == (MAX-1))
  19. {
  20. printf("\nSTACK FULL");
  21. }
  22. else
  23. {
  24. ++s->top;
  25. s->data[s->top]=item;
  26. }
  27. }
  28. int pop(struct stack* s)
  29. {
  30. int ret=EMPTY;
  31. if(s->top == EMPTY)
  32. printf("\nSTACK EMPTY");
  33. else
  34. {
  35. ret= s->data[s->top];
  36. --s->top;
  37. }
  38. return ret;
  39. }
  40. void display(struct stack s)
  41. {
  42. while(s.top != EMPTY)
  43. {
  44. printf("\n%d",s.data[s.top]);
  45. s.top--;
  46. }
  47. }
  48. int evaluate(char *postfix)
  49. {
  50. char *p;
  51. struct stack stk;
  52. int op1,op2,result;
  53. emptystack(&stk);
  54. p = &postfix[0];
  55. while(*p != '\0')
  56. {
  57. while(*p == ' ' || *p == '\t')
  58. {
  59. p++;
  60. }
  61. if(isdigit(*p))
  62. {
  63. push(&stk,*p - 48);
  64. }
  65. else
  66. {
  67. op1 = pop(&stk);
  68. op2 = pop(&stk);
  69. switch(*p)
  70. {
  71. case '+':
  72. result = op2 + op1;
  73. break;
  74. case '-':
  75. result = op2 - op1;
  76. break;
  77. case '/':
  78. result = op2 / op1;
  79. break;
  80. case '*':
  81. result = op2 * op1;
  82. break;
  83. case '%':
  84. result = op2 % op1;
  85. break;
  86. default:
  87. return 0;
  88. }
  89. push(&stk,result);
  90. }
  91. p++;
  92. }
  93. result = pop(&stk);
  94. return result;
  95. }
  96. int main()
  97. {
  98. char exp[MAX];
  99. fgets(exp, sizeof(exp), stdin);
  100. exp[strlen(exp) - 1] = '\0';
  101. printf("%s EQUALS %d\n",exp,evaluate(&exp[0]));
  102. system ("pause");
  103. return 0;
  104. }
  105. /*
  106. input: 24 24 +
  107. output: 24 24 + EQUALS 6
  108. 預期正確結果 48
  109. */
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
STACK EMPTY EQUALS -1