Pagini recente » Cod sursa (job #835021) | Cod sursa (job #3331956) | Cod sursa (job #2559556) | Cod sursa (job #533841) | Cod sursa (job #3331954)
#include <fstream>
#include <cstring>
using namespace std;
const int PRIORIMAX = 2, // 0 -> +, - ; 1 -> *, / ; 2 -> ^
LGMAX = 1e5 + 1;
const char op[3][3] = { "+-", "*/", "" };
ifstream fin("evaluareuare.in");
ofstream fout("evaluareuare.out");
char s[LGMAX], *p;
struct nod
{
int val;
char op;
nod *st, *dr;
nod(int x = 0, char y = 0, nod *z = 0, nod *t = 0)
{
val = x, op = y, st = z, dr = t;
}
} *rad;
nod *expresie(int priori)
{
nod *x, *y;
if(priori == PRIORIMAX)
{
if(*p == '(')
{
++p, x = expresie(0), ++p;
}
else
{
for(x = new nod(); *p >= '0' && *p <= '9'; ++p)
x->val = x->val * 10 + *p - '0';
}
}
else
{
for(x = expresie(priori + 1); *p && strchr(op[priori], *p); x = y)
y = new nod(0, *p++, x, expresie(priori + 1));
}
return x;
}
int evaluare(nod *n)
{
switch(n->op)
{
case '+':
return evaluare(n->st) + evaluare(n->dr);
case '-':
return evaluare(n->st) - evaluare(n->dr);
case '*':
return evaluare(n->st) * evaluare(n->dr);
case '/':
return evaluare(n->st) / evaluare(n->dr);
default:
return n->val;
}
}
int main()
{
fin >> s;
p = s;
rad = expresie(0);
fout << evaluare(rad);
return 0;
}