Pagini recente » Cod sursa (job #571916) | Cod sursa (job #1362120) | Cod sursa (job #2657795) | Cod sursa (job #2099133) | Cod sursa (job #2855032)
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001];
int l;
stack <int> operanzi;
stack <char> operatori;
int prioritate(char c)
{
if(c == '/' || c == '*')
return 2;
if(c == '-' || c == '+')
return 1;
return 0;
}
int se_poate(char c1, char c2)
{
if(prioritate(c2) < prioritate(c1))
return 1;
return 0;
}
int in_numar(char *s, int &i)
{
int nr = 0;
for(; s[i] >= '0' && s[i] <= '9'; ++i)
{
//cout << i << ' ';
nr = nr * 10 + (s[i] - '0');
}
return nr;
}
int calcul(int x, int y, char c)
{
if(c == '+')
return x + y;
if(c == '-')
return x - y;
if(c == '*')
return x * y;
if(c == '/')
return x / y;
}
int evaluare(char *s, int l)
{
for(int i = 0; i < l; ++i)
{
if(strchr("/*+-", s[i]) && operatori.empty())
operatori.push(s[i]);
else if(s[i] >= '0' && s[i] <= '9')
{
int nr = in_numar(s, i);
operanzi.push(nr);
i--;
}
else if(s[i] == ')')
{
while(operatori.top() != '(')
{
int y = operanzi.top();
operanzi.pop();
int x = operanzi.top();
operanzi.pop();
int rez = calcul(x, y, operatori.top());
operatori.pop();
operanzi.push(rez);
}
operatori.pop();
}
else if(s[i] == '(')
operatori.push(s[i]);
else if(strchr("/*+-", s[i]))
{
if(se_poate(s[i], operatori.top()))
operatori.push(s[i]);
else
{
while(!operatori.empty() && !se_poate(s[i], operatori.top()))
{
int y = operanzi.top();
operanzi.pop();
int x = operanzi.top();
operanzi.pop();
int rez = calcul(x, y, operatori.top());
operatori.pop();
operanzi.push(rez);
}
operatori.push(s[i]);
}
}
}
while(!operatori.empty())
{
int y = operanzi.top();
operanzi.pop();
int x = operanzi.top();
operanzi.pop();
int rez = calcul(x, y, operatori.top());
operatori.pop();
operanzi.push(rez);
}
return operanzi.top();
}
int main()
{
fin.getline(s, 256);
l = strlen(s);
fout << evaluare(s, l);
return 0;
}