就是给你一个表达式,有(+-*/) 以及数字组成,不过这个题比较简单就是 数字最多是两位数,(就可以直接算了, 如果没有限制的话, 就可以继续用一个栈来保存数字)
/*
Accepted 3774 C++ 2.0K 0'00.00" 1356K
*/
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
stack<int>num_s;// 存放数字的栈
stack <char> op_s;//存放操作符的栈
void clear_s()
{//栈清空初始化
while(!num_s.empty())
num_s.pop();
while(!op_s.empty())
op_s.pop();
}
char Precede(char a,char b)
{//比较操作符的优先级
if(a=='+'||a=='-'){
if(b=='*'||b=='/'||b=='(') return '<';else return '>';
}
if(a=='*'||a=='/'){
if(b=='(') return '<';else return '>';
}
if(a=='('){
if(b==')') return '=';else return '<';
}
if(a==')') return '>';
if(a=='#'&&b=='#') return '=';
else return '<';
}
int Opera(int a,int b,char op)
{
if(op=='+') return a+b;
if(op=='-') return a-b;
if(op=='*') return a*b;
else return a/b;
}
char ch[105];
int len;
int main()
{
while(cin>>ch)
{
clear_s();
op_s.push('#');
len=strlen(ch);
ch[len]='#';ch[len+1]='\0';//额外加一个#作为结束判读
int i=0;
while(ch[i]!='#'||op_s.top()!='#')
{
int tmp=0;
if(isdigit(ch[i]))
{//处理数字
if(i<len-1&&isdigit(ch[i+1]))
{
tmp+=(ch[i]-'0')*10+(ch[i+1]-'0');
i++;
}
else tmp+=ch[i]-'0';
i++;
num_s.push(tmp);
}
else
{//处理操作符
char cmp=Precede(op_s.top(),ch[i]);
if(cmp=='<')
{//即将入站的操作符优先级别高,入栈
op_s.push(ch[i]);i++;
}
else if(cmp=='=')
{//一般这个处理右括号
op_s.pop();i++;
}
else
{//栈顶操作符优先级高,开始处理运算
char op=op_s.top();
op_s.pop();
int n1=num_s.top();
num_s.pop();
int n2=num_s.top();
num_s.pop();
int res=Opera(n2,n1,op);
num_s.push(res);
}
}
}
cout<<num_s.top()<<endl;
}
}