int Calc(int a, int b, char oprt)
{
switch(oprt)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
}
int expr(char a[])
{
char ch, last_oprt;
int c, d;
CStack<int> oprd;
CStack<char> oprt;
while(ch=*a++)
{
if(ch == '(')
{
oprt.Push(ch);
}
else if(ch == ')')
{
while(oprt.IsEmpty() == false)
{
last_oprt = oprt.Pop();
if(last_oprt == '(') // 遇到匹配的左括号退出
break;
d = oprd.Pop();
c = oprd.Pop();
oprd.Push(Calc(c, d, last_oprt));
}
}
else if(ch == '+' || ch == '-')
{
if(oprt.IsEmpty() == false)
{
last_oprt = oprt.Top();
if(last_oprt != '(')
{
d = oprd.Pop();
c = oprd.Pop();
oprd.Push(Calc(c, d, last_oprt));
oprt.Pop();
}
}
oprt.Push(ch);
}
else if(ch == '*' || ch == '/')
{
if(oprt.IsEmpty() == false)
{
last_oprt = oprt.Top();
if(last_oprt == '*' || last_oprt == '/')
{
d = oprd.Pop();
c = oprd.Pop();
oprd.Push(Calc(c, d, last_oprt));
oprt.Pop();
}
}
oprt.Push(ch);
}
else
{
oprd.Push(ch-'0');
}
}
while(oprt.IsEmpty() == false)
{
last_oprt = oprt.Pop();
if(last_oprt == '(')
break;
else
{
d = oprd.Pop();
c = oprd.Pop();
oprd.Push(Calc(c, d, last_oprt));
}
}
return oprd.Pop();
}
评论