#include <iostream>
#include<stack>
using namespace std;
//+、 -、 *、 /、(、 )、#//
char Relation[7][7]= { {'>','>','<','<','<','>','>'},//栈顶元素 +
{'>','>','<','<','<','>','>'},// -
{'>','>','>','>','<','>','>'},// *
{'>','>','>','>','<','>','>'},// /
{'<','<','<','<','<','=','>'},// (
{'>','>','>','>','=','>','>'},// )
{'<','<','<','<','<','<','='}};// #
bool isOperators(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#')
return true;
else
return false;
}
int ConvertToIndex(char opr)
{
int index;
switch (opr)
{
case '+':
index = 0;
break;
case '-':
index = 1;
break;
case '*':
index = 2;
break;
case '/':
index = 3;
break;
case '(':
index = 4;
break;
case ')':
index = 5;
break;
case '#':
index = 6;
break;
}
return index;
}
char precede(char op1,char op2)
{
int num1=ConvertToIndex(op1);
int num2=ConvertToIndex(op2);
return Relation[num1][num2];
}
int Operate(int num1,char op,int num2)
{
int ret;
switch(op)
{
case '+':
ret=num1+num2;
break;
case '-':
ret=num1-num2;
break;
case '*':
ret=num1*num2;
break;
case '/':
ret=num1/num2;
break;
}
return ret;
}
int caculate (string str)
{
stack<int> spnd;
stack<char> sptr;
int i=0;
str+='#';
char ch=str[i++];
sptr.push('#');
while(sptr.top()!='#'||ch!='#')
{
if(!isOperators(ch))
{
int a=ch-'0';
spnd.push(a);
ch=str[i++];
}
else
{
char exp=precede(sptr.top(),ch);
if(exp=='>')//栈顶优先级大
{
int num2=spnd.top();
spnd.pop();
int num1=spnd.top();
spnd.pop();
char op=sptr.top();
sptr.pop();
int ret=Operate(num1,op,num2);
spnd.push(ret);
}
if(exp=='<')//栈顶优先级小
{
sptr.push(ch);
ch=str[i++];
}
if(exp=='=')//括号匹配弹出
{
sptr.pop();
ch=str[i++];
}
}
}
return spnd.top();
}
int main ()
{
char chr[1025];
cin>>chr;
string s=string (chr);
int res;
int flag=1;
for(int i=0;i<s.size();i++)
{
if(!(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='('||s[i]==')'||isdigit(s[i])))
{
flag=0;
break;
}
}
if(flag)
{
res=caculate (s);
flag=1;
cout<<res<<endl;
}
else
cout<<false<<endl;
return 0;
}
知识点isdigit(s[i])检查参数c是否为阿拉伯数字0到9。运算符的优先关系比较