Pagini recente » Cod sursa (job #816390) | Cod sursa (job #2880382) | Cod sursa (job #1513077) | Cod sursa (job #117106) | Cod sursa (job #837143)
Cod sursa(job #837143)
#include<fstream>
#include<stack>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char e[100004],opcrt;
stack<char>op;
stack<int>v;
int n,a,b,i;
void operatie(){
a=v.top();
v.pop();
b=v.top();
v.pop();
opcrt=op.top();
op.pop();
switch(opcrt)
{
case '+':{v.push(a+b);break;}
case '-':{v.push(b-a);break;}
case '*':{v.push(a*b);break;}
case '/':{v.push(b/a);break;}
}
}
int numar(){
int x=i;
int nr=0;
while('0'<=e[x] && e[x]<='9')
{
nr=nr*10+e[x++]-'0';
}
i=x-1;
return nr;
}
int main(){
f>>e;
i=0;
while(e[i]!='\0')
{
switch(e[i])
{
case '(':{
op.push(e[i]);
break;}
case ')':
while(op.top()!='(')
{
operatie();
}
op.pop();break;
case '+':case '-':{
while(!op.empty() && op.top()!='(')
{
operatie();
}
op.push(e[i]);break;
}
case'*':case'/':
{ if(!op.empty()){
if(op.top()=='/'){
a=v.top();v.pop();b=v.top();v.pop();
v.push(b/a);break;}
else if(op.top()=='*'){
a=v.top();v.pop();b=v.top();v.pop();
v.push(b*a);break;}
}
op.push(e[i]);
break;
}
default:{
a=numar();
v.push(a);
}
}
i++;
}
while(!op.empty())
{
operatie();
};
g<<v.top();
return 0;
}