接尾辞式算数の評価
3166 ワード
テスト:
:1*2+3*4-6/3
:12*34*+63/-
#include<stdio.h>
#include<string.h>
int OP(int a,int b,char c)
{
switch(c)
{
case '+' : return a+b;break;
case '-' : return a-b;break;
case '*' : return a*b;break;
case '/' :
if(b!=0)
return a/b;
else
printf("ERROR!
");
break;
}
}
int com(char exp[])
{
int i=0,top=-1,stack[100],c,a,b;
while(exp[i]!='\0')
{
if(exp[i]>='0'&&exp[i]<='9')
stack[++top]=exp[i]-'0';
else
{
b=stack[top--];
a=stack[top--];
c=OP(a,b,exp[i]);
stack[++top]=c;
}
++i;
}
return stack[top];
}
void main()
{
char exp[100];
int r;
gets(exp);
r=com(exp);
printf("result=%d
",r);
}