#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <cstring>
#define MAX 50
#define EMPTY -1
struct stack
{
int data[MAX];
int top;
};
void emptystack(struct stack* s)
{
s->top = EMPTY;
}
void push(struct stack* s,int item)
{
if(s->top == (MAX-1))
{
printf("\nSTACK FULL");
}
else
{
++s->top;
s->data[s->top]=item;
}
}
int pop(struct stack* s)
{
int ret=EMPTY;
if(s->top == EMPTY)
printf("\nSTACK EMPTY");
else
{
ret= s->data[s->top];
--s->top;
}
return ret;
}
void display(struct stack s)
{
while(s.top != EMPTY)
{
printf("\n%d",s.data[s.top]);
s.top--;
}
}
int evaluate(char *postfix)
{
char *p;
struct stack stk;
int op1,op2,result;
emptystack(&stk);
p = &postfix[0];
while(*p != '\0')
{
while(*p == ' ' || *p == '\t')
{
p++;
}
if(isdigit(*p))
{
push(&stk,*p - 48);
}
else
{
op1 = pop(&stk);
op2 = pop(&stk);
switch(*p)
{
case '+':
result = op2 + op1;
break;
case '-':
result = op2 - op1;
break;
case '/':
result = op2 / op1;
break;
case '*':
result = op2 * op1;
break;
case '%':
result = op2 % op1;
break;
default:
return 0;
}
push(&stk,result);
}
p++;
}
result = pop(&stk);
return result;
}
int main()
{
char exp[MAX];
fgets(exp, sizeof(exp), stdin);
exp[strlen(exp) - 1] = '\0';
printf("%s EQUALS %d\n",exp,evaluate(&exp[0]));
system ("pause");
return 0;
}
/*
input: 24 24 +
output: 24 24 + EQUALS 6
預期正確結果 48
*/
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxjdHlwZS5oPgojaW5jbHVkZSA8c3RkbGliLmg+CiNpbmNsdWRlIDxjc3RyaW5nPiAKI2RlZmluZSBNQVggNTAKI2RlZmluZSBFTVBUWSAtMQpzdHJ1Y3Qgc3RhY2sKewoJaW50IGRhdGFbTUFYXTsKCWludCB0b3A7Cn07CnZvaWQgZW1wdHlzdGFjayhzdHJ1Y3Qgc3RhY2sqIHMpCnsKCXMtPnRvcCA9IEVNUFRZ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