Pagini recente » Cod sursa (job #1134313) | Cod sursa (job #2488110) | Cod sursa (job #3233677) | Cod sursa (job #1686765) | Cod sursa (job #1759638)
#include<iostream>
#include<fstream>
#include<string>
#include<stack>
#include<cctype>
using namespace std;
fstream fin("evaluare.in",ios::in),fout("evaluare.out",ios::out);
int val[200];
string s;
stack<int> nr;
stack<char> op;
char c;
void rezolvare();
int digit(int& poz);
void evaluare();
int main()
{
val['(']=0;
val[')']=0;
val['+']=1;
val['-']=1;
val['*']=2;
val['/']=2;
fin>>s;
rezolvare();
}
void evaluare()
{
int a,b;
b=nr.top();nr.pop();
a=nr.top();nr.pop();
c=op.top();op.pop();
if(c=='+') nr.push(a+b);
if(c=='-') nr.push(a-b);
if(c=='/') nr.push(a/b);
if(c=='*') nr.push(a*b);
}
int digit(int& i)
{
int nr=0;
for( ;i<s.size() && isdigit(s[i]);i++) nr=nr*10+s[i]-'0';
i--;
return nr;
}
void rezolvare()
{
int i;
for(i=0;i<s.size();i++)
{
if(isdigit(s[i]))
{
nr.push(digit(i));
}
else
{
if(s[i]=='(')
{
op.push(s[i]);
}
else
{
if(s[i]==')')
{
while(op.empty()==0 && op.top()!='(') evaluare();
if(op.empty()==0 && op.top()=='(') op.pop();
}
else
{
while(op.empty()==0 && val[op.top()]>=val[s[i]]) evaluare();
op.push(s[i]);
}
}
}
}
while(op.empty()==0) evaluare();
fout<<nr.top()<<"\n";
}