Pagini recente » Cod sursa (job #590790) | Cod sursa (job #2748421) | Cod sursa (job #2818051) | Cod sursa (job #1124578) | Cod sursa (job #1919487)
#include<fstream>
#include<stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack<int>nums;
stack<char>ops;
void operation()
{
char op=ops.top();
ops.pop();
int b=nums.top();
nums.pop();
int a=nums.top();
nums.pop();
if(op=='+') nums.push(a+b);
if(op=='-') nums.push(a-b);
if(op=='*') nums.push(a*b);
if(op=='/') nums.push(a/b);
}
int priority(char c)
{
if(c=='+'||c=='-') return 1;
if(c=='*'||c=='/') return 2;
return 0;
}
void solve()
{
int p,x;
ops.push('1');
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
ops.push(s[i]);
else
{
if(s[i]==')')
{
while(ops.top()!='(')
operation();
ops.pop();
}
else
{
p=priority(s[i]);
if(p)
{
while(priority(ops.top())>=p)
operation();
ops.push(s[i]);
}
else
{
for(x=0;isdigit(s[i]);i++)
x=x*10+(s[i]-'0');
nums.push(x);
i--;
}
}
}
}
while(ops.size()>1)
operation();
}
int main()
{
fin>>s;
solve();
fout<<nums.top();
}