Cod sursa(job #1250694)
Utilizator | Data | 28 octombrie 2014 13:43:51 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 30 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 5.03 kb |
#include<fstream>
#include<iostream>
#include<stack>
using namespace std;
stack<int> x;
stack<char> c;
int main()
{
ifstream si;
si.open("evaluare.in");
ofstream so;
so.open("evaluare.out");
char a;
int z;
int i,d,e,f;
while(si>>a)
{
if('0'<=a&&a<='9')
{
z=a-'0';
while(si>>a&&'0'<=a&&a<='9')
{
z=z*10+a-'0';
}
x.push(z);
// cout<<z<<endl;
}
if(si.eof()==true)
break;
// cout<<a<<endl;
if(a=='+'||a=='-'||a=='*'||a=='/'||a=='(')
{
//cout<<endl<<c.size()<<endl;
c.push(a);
//cout<<endl<<c.size()<<' '<<c.top()<<endl;
}
else
{
//cout<<c.size()<<endl;
//cout<<i;
//cout<<c.top();
while(c.top()!='(')
{
a=c.top();
c.pop();
d=x.top();
x.pop();
e=x.top();
x.pop();
if(c.top()=='*')
{
f=x.top();
x.pop();
switch(a)
{
case '+':x.push(d+e*f); break;
case '-':x.push(e*f-d); break;
case '*':x.push(d*e*f); break;
case '/':x.push(e*f/d); break;
}
c.pop();
}
else
if(c.top()=='/')
{
f=x.top();
x.pop();
switch(a)
{
case '+':x.push(d+f/e); break;
case '-':x.push(f/e-d); break;
case '*':x.push(f/e*d); break;
case '/':x.push(f/e/d); break;
}
c.pop();
}
else
{
switch(a)
{
case '+':x.push(d+e); break;
case '-':x.push(e-d); break;
case '*':x.push(d*e); break;
case '/':x.push(e/d); break;
}
}
}
c.pop();
}
}
while(c.size()>0)
{
a=c.top();
c.pop();
// cout<<a<<' '<<c.size()<<endl;
d=x.top();
x.pop();
e=x.top();
x.pop();
if(c.size()>0)
{
if(c.top()=='*')
{
f=x.top();
// cout<<f<<c.top()<<e<<a<<d<<'='<<f*e+d<<endl;
x.pop();
switch(a)
{
case '+':x.push(f*e+d); break;
case '-':x.push(f*e-d); break;
case '*':x.push(f*e*d); break;
case '/':x.push(f*e/d); break;
}
c.pop();
}
else
if(c.top()=='/')
{
f=x.top();
x.pop();
switch(a)
{
case '+':x.push(f/e+d); break;
case '-':x.push(f/e-d); break;
case '*':x.push(f/e*d); break;
case '/':x.push(f/e/d); break;
}
c.pop();
}
else
{
switch(a)
{
case '+':x.push(d+e); break;
case '-':x.push(e-d); break;
case '*':x.push(d*e); break;
case '/':x.push(e/d); break;
}
}
// cout<<'a'<<endl;
}
else
{
// cout<<a<<' '<<d<<' '<<e;
switch(a)
{
case '+':x.push(d+e); break;
case '-':x.push(e-d); break;
case '*':x.push(d*e); break;
case '/':x.push(e/d); break;
}
//cout<<'b';
}
// cout<<x.top()<<endl;
}
so<<x.top();
}