Pagini recente » Cod sursa (job #2307719) | Cod sursa (job #2690898) | Cod sursa (job #2323497) | Cod sursa (job #2713081) | Cod sursa (job #348221)
Cod sursa(job #348221)
#include <stdio.h>
#include <stack>
#define MAXN 100002
using namespace std;
int prec[255];
struct exp
{
bool numar;
int val;
char opr;
};
stack<char> opr;
exp a[MAXN];
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
prec['+'] = 1;
prec['-'] = 1;
prec['*'] = 2;
prec['/'] = 2;
prec['('] = -10;
char aux;
int nr,nrt =0;
while (!feof(stdin))
{
scanf("%c",&aux);
if (aux!= '\n' && aux!='\0')
{
if (aux>='0' && aux<='9')
{
nr = 0;
while (aux>='0' && aux<='9' && aux != '\n' && aux != '\0')
{
nr*=10;
nr+=aux-'0';
scanf("%c",&aux);
}
nrt++;
a[nrt].numar = true;
a[nrt].val = nr;
}
if (aux != '\n' && aux!='\0')
{
if (aux == '(')
{
opr.push(aux);
}
else if (aux == ')')
{
while (opr.top()!='(')
{
nrt++;
a[nrt].numar = false;
a[nrt].opr = opr.top();
opr.pop();
}
opr.pop();
}
else if (opr.empty())
{
opr.push(aux);
}
else
{
while (prec[aux]<=prec[opr.top()] && !opr.empty())
{
nrt++;
a[nrt].numar = false;
a[nrt].opr = opr.top();
opr.pop();
if (opr.empty())
{
break;
}
}
opr.push(aux);
}
}
}
}
while (!opr.empty())
{
nrt++;
a[nrt].numar = false;
a[nrt].opr = opr.top();
opr.pop();
}
stack<int> s;
int t1,t2,i;
for (i=1;i<=nrt;i++)
{
if (a[i].numar)
{
s.push(a[i].val);
}
else
{
t2 = s.top();
s.pop();
t1 = s.top();
s.pop();
switch(a[i].opr)
{
case '+':
s.push(t1+t2);
break;
case '-':
s.push(t1-t2);
break;
case '*':
s.push(t1*t2);
break;
case '/':
s.push(t1/t2);
break;
}
}
}
printf("%d",s.top());
return 0;
}