Pagini recente » Monitorul de evaluare | Cod sursa (job #399081) | Cod sursa (job #399089) | Monitorul de evaluare | Cod sursa (job #3346637)
#include <bits/stdc++.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string s;
stack<int> nr;
stack<char> op;
int i;
int inainte(char c) {
if(c=='+' || c=='-') return 1;
if(c=='*' || c=='/') return 2;
return 0;
}
int calc() {
int b = nr.top();
nr.pop();
int a = nr.top();
nr.pop();
char c = op.top();
op.pop();
if(c=='+')
return a+b;
if(c=='-')
return a-b;
if(c=='*')
return a*b;
return a/b;
}
int getnr() {
int r=0;
while(i<s.size()&&isdigit(s[i]))
r = r*10 + (s[i]-'0'), i++;
i--;
return r;
}
int main() {
f >> s;
for(i=0; i<s.size(); i++) {
if(isdigit(s[i]))
{
nr.push(getnr());
}
else if(s[i]=='(')
{
op.push('(');
}
else if(s[i]==')')
{
while(!op.empty()&&op.top()!='(')
nr.push(calc());
op.pop();
}
else
{
if(s[i]=='-'&&(i==0||s[i-1]=='('))
nr.push(0);
while(!op.empty()&&inainte(op.top())>=inainte(s[i]))
nr.push(calc());
op.push(s[i]);
}
}
while(!op.empty())
nr.push(calc());
g << nr.top();
return 0;
}