您的位置:首页 > 其它

表达式求值

2016-03-24 21:07 323 查看


题目描述

利用栈来实现含有加,减,乘,除等基本运算,输出表达式的值


输入

3*(15/5)+8=


输出

17


样例输入

24-(6+(27/3)*2)=


样例输出

0


AC代码:

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
int main()
{
int T,i,len;
int x,y,flat;
char str[100];
stack<int>n;
stack<char>c;
scanf("%s",str);
len=strlen(str);
for(i=0;i<len;){
if(str[i]>='0'&&str[i]<='9'){
flat=0;
while(str[i]>='0'&&str[i]<='9'){
flat=flat*10+str[i]-'0';
i++;
}
n.push(flat);
}
else if(str[i]=='('){
c.push(str[i]);
i++;
}
else if(str[i]=='+'||str[i]=='-'){
if(!c.empty()&&c.top()!='('){
x=n.top();
n.pop();
y=n.top();
n.pop();
if(c.top()=='+')n.push(x+y);
else if(c.top()=='-')n.push(y-x);
else if(c.top()=='*')n.push(x*y);
else if(c.top()=='/')n.push(y/x);
c.pop();
}
else{
c.push(str[i]);
i++;
}
}
else if(str[i]=='*'||str[i]=='/'){
if(!c.empty()&&c.top()!='('){
if(c.top()=='+'||c.top()=='-'){
c.push(str[i]);
i++;continue;
}
else{
x=n.top();
n.pop();
y=n.top();
n.pop();
if(c.top()=='*')n.push(x*y);
else n.push(y/x);
c.pop();
}
}
else{
c.push(str[i]);
i++;
}
}
else if(str[i]==')'){
while(c.top()!='(')
{
x=n.top();
n.pop();
y=n.top();
n.pop();
if(c.top()=='-')
n.push(y-x);
else if(c.top()=='+')
n.push(x+y);
else if(c.top()=='*')
n.push(x*y);
else
n.push(y/x);
c.pop();
}
c.pop();
i++;
}
else if(str[i]=='=')
{
if(!c.empty())
{
while(!c.empty())
{
x=n.top();
n.pop();
y=n.top();
n.pop();
if(c.top()=='-'){
n.push(y-x);
i++;
}
else if(c.top()=='+'){
n.push(x+y);
i++;
}
else if(c.top()=='*'){
n.push(x*y);
i++;
}
else if(c.top()=='/'){
n.push(y/x);
i++;
}
c.pop();
}
}
else i++;
}
}
printf("%d\n",n.top());
n.empty();
c.empty();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: