注:支持+,-,*,/,(,),程序简陋,请确保输入正确的式子,不需要输入等号
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <list>
#include <map>
#include <string>
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 50
int intopost(char *infix,char *postfix)
{
stack<int>s;
int i=0,j=0;
int e=0;
while(infix[i]!='\0')
{
while(infix[i]>='0' && infix[i]<='9')
{
postfix[j++]=infix[i];
i++;
if(infix[i]<'0' || infix[i]>'9')
postfix[j++]=' ';
}
if(infix[i]==')')
{
e=s.top();
s.pop();
while(e!='(')
{
postfix[j++]=e;
postfix[j++]=' ';
e=s.top();
s.pop();
}
}
else if(infix[i]=='+' || infix[i]=='-')
{
if(s.empty())
{
s.push(infix[i]);
}
else
{
do
{
e=s.top();
s.pop();
if(e=='(')
s.push(e);
else
{
postfix[j++]=e;
postfix[j++]=' ';
}
}while(!s.empty() && e!='(');
s.push(infix[i]);
}
}
else if(infix[i]=='*' || infix[i]=='/' || infix[i]=='(')
{
s.push(infix[i]);
}
else if(infix[i]=='\0')
break;
else
return ERROR;
i++;
}
while(!s.empty())
{
e=s.top();
s.pop();
postfix[j++]=e;
postfix[j++]=' ';
}
return OK;
}
int calculate(char *postfix)
{
stack<int>ss;
char *op;
char *buf=postfix;
int d,e,f;
int ans=0;
while((op=strtok(buf," "))!=NULL)
{
buf=NULL;
switch(op[0])
{
case '+':
d=ss.top();
ss.pop();
e=ss.top();
ss.pop();
f=d+e;
ss.push(f);
break;
case '-':
d=ss.top();
ss.pop();
e=ss.top();
ss.pop();
f=e-d;
ss.push(f);
break;
case '*':
d=ss.top();
ss.pop();
e=ss.top();
ss.pop();
f=e*d;
ss.push(f);
break;
case '/':
d=ss.top();
ss.pop();
e=ss.top();
ss.pop();
f=e/d;
ss.push(f);
break;
default:
d=atoi(op);
ss.push(d);
break;
}
}
ans=ss.top();
ss.pop();
return ans;
}
int main()
{
char infix[MAXSIZE];
char postfix[MAXSIZE];
int ans=0;
cin >>infix;
intopost(infix,postfix);
ans=calculate(postfix);
cout <<ans <<endl;
return 0;
}
//calc::2+(1+(1*1)*(1+(1+1)))