Pagini recente » Cod sursa (job #1087295) | Cod sursa (job #644225) | Cod sursa (job #659769) | Cod sursa (job #2760405) | Cod sursa (job #2857176)
#include <bits/stdc++.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
stack <int> nr;
stack <char> op;
char sir[100001];
void eval()
{
int x=nr.top();
nr.pop();
int y=nr.top();
nr.pop();
char c;
c=op.top();
op.pop();
cout<<'\n'<<"op: "<<(char)c<<'\n';
if(c=='+') nr.push(x+y);
else if(c=='-') nr.push(y-x);
else if(c=='*') nr.push(y*x);
else nr.push(y/x);
cout<<"x="<<x<<'\n'<<"y="<<y<<'\n'<<"nr="<<nr.top()<<'\n'<<'\n';
}
int rez(char s[100005], int k)
{
int n=k;
for(int i=0; i<n; i++)
{
if(isdigit(s[i]))
{
int x=0;
while(i<n && isdigit(s[i]))
{
x=x*10+s[i]-'0';
i++;
}
i--;
nr.push(x);
cout<<"x= "<<x<<'\n';
}
else if(s[i]=='(') op.push(s[i]);
else if(s[i]==')' && !op.empty())
{
if(op.top()=='(') op.pop();
else while(!op.empty() && op.top()!='(' && !nr.empty()) eval();
op.pop();
}
else if(op.empty()) op.push(s[i]);
else if(s[i]=='*')
{
while(!op.empty() && op.top()=='/') eval();
op.push(s[i]);
}
else if(s[i]=='/')
{
while(!op.empty() && (op.top()=='*' || op.top()=='/')) eval();
op.push(s[i]);
}
else if(s[i]=='-')
{
while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
op.push(s[i]);
}
else if(s[i]=='+')
{
while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
op.push(s[i]);
}
}
while(!op.empty()) eval();
return nr.top();
}
int main()
{
f>>sir;
g<<rez(sir, strlen(sir));
return 0;
}