Pagini recente » Cod sursa (job #188068) | Cod sursa (job #1684579) | Cod sursa (job #692964) | Istoria paginii runda/jevfkephfiberibereer | Cod sursa (job #2109853)
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
int numar(char x)
{
return x-48;
}
int calcul(int x, int y, char a)
{
if (a=='-')
return x-y;
if (a=='+')
return x+y;
if (a=='*')
return x*y;
return x/y;
}
int grad(char x)
{
if (x=='+')
return 1;
if (x=='-')
return 1;
if (x=='*')
return 2;
if (x=='/')
return 2;
if (x=='(')
return 3;
return 4;
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
stack <int> numere;
stack <char> operatori;
char a[100010];
int i;
fin.getline(a, 100010);
for (i=0; a[i]; i++)
{
if (isdigit(a[i]))
{
int num=0;
while(isdigit(a[i]))
{
num=num*10+numar(a[i]);
i++;
}
numere.push(num);
i--;
}
else
{
if (grad(a[i])==4)
{
int rez;
rez=numere.top();
numere.pop();
while(operatori.top()!='(')
{
rez=calcul(numere.top(), rez, operatori.top());
numere.pop();
operatori.pop();
}
operatori.pop();
numere.push(rez);
}
else
{
if (operatori.empty()==0)
{
if (grad(operatori.top())==2 && grad(a[i])==1)
{
int rez;
rez=numere.top();
numere.pop();
while (grad(operatori.top())>1)
{
rez=calcul(numere.top(), rez, operatori.top());
numere.pop();
operatori.pop();
if (operatori.empty())
break;
}
numere.push(rez);
operatori.push(a[i]);
}
else
{
if (operatori.empty()==0)
{
if ((a[i]=='/' && operatori.top()=='/') || (a[i]=='-' && operatori.top()=='-'))
{
int rez=numere.top();
numere.pop();
rez=calcul(numere.top(), rez, operatori.top());
operatori.pop();
numere.push(rez);
}
}
operatori.push(a[i]);
}
}
else
{
if (operatori.empty()==0)
{
if ((a[i]=='/' && operatori.top()=='/') || (a[i]=='-' && operatori.top()=='-'))
{
int rez=numere.top();
numere.pop();
rez=calcul(numere.top(), rez, operatori.top());
operatori.pop();
numere.push(rez);
}
}
operatori.push(a[i]);
}
}
}
}
int rez;
rez=numere.top();
numere.pop();
while(operatori.empty()==0)
{
rez=calcul(numere.top(), rez, operatori.top());
numere.pop();
operatori.pop();
}
fout << rez;
return 0;
}