Pagini recente » Cod sursa (job #1943642) | Cod sursa (job #2777454) | Cod sursa (job #1485264) | Cod sursa (job #2543019) | Cod sursa (job #2157271)
#include <bits/stdc++.h>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
const int ASCII_MAX = 47;
char ch, last;
int priority[ASCII_MAX + 2];
stack<char> op;
stack<int> polo;
void evaluare()
{
int num = polo.top();
char semn = op.top();
op.pop(); polo.pop();
switch(semn)
{
case '+':
polo.top() += num;
break;
case '-':
polo.top() -= num;
break;
case '*':
polo.top() *= num;
break;
case '/':
polo.top() /= num;
}
}
int main()
{
priority['+'] = priority['-'] = 1;
priority['*'] = priority['/'] = 2;
priority['('] = 0;
int nr;
last = nr = 0;
while(in >> ch)
{
if(isdigit(last) && !isdigit(ch))
{
polo.push(nr);
nr = 0;
}
if(isdigit(ch))
nr = nr * 10 + ch - '0';
else if(ch == ')')
{
while(!op.empty() && op.top() != '(')
evaluare();
op.pop();
}
else
{
if(ch == '(')
{
op.push('(');
continue;
}
while(!op.empty() && priority[ch] <= priority[op.top()])
evaluare();
op.push(ch);
}
last = ch;
}
if(nr)
polo.push(nr);
while(!op.empty())
evaluare();
out << polo.top() << '\n';
return 0;
}