Pagini recente » Cod sursa (job #3279327) | Cod sursa (job #1555329) | Cod sursa (job #1260186) | Cod sursa (job #2461783) | Cod sursa (job #2733977)
#include <fstream>
#include <cstring>
#include <stack>
#include <string>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001], po[100001];
int z, i, x1, x2, x, k, parl, p10, dv;
int counter (int a)
{
int r = 0;
while (a > 0)
{
a = a/10;
r++;
}
if (r == 0) return 1;
return r;
}
int main()
{
fin >> s;
stack<pair<char, int>> S;
for (i = 0; i < strlen(s); i++)
{
if (strchr("1234567890", s[i]) != NULL)
{
po[k++] = s[i];
if (strchr("1234567890", s[i + 1]) == NULL || s[i + 1] == '\0')
po[k++] = ' ';
}
else if (s[i] == '+' || s[i] == '-')
{
int prec = 2 * parl;
if (!S.empty() && S.top().second > prec)
{
while (!S.empty() && S.top().second > prec)
{
po[k++] = S.top().first;
po[k++] = ' ';
S.pop();
}
}
S.push(make_pair(s[i], prec));
}
else if (s[i] == '*' || s[i] == '/')
{
int prec = 2 * parl + 1;
if (!S.empty() && S.top().second > prec)
{
while (!S.empty() && S.top().second > prec)
{
po[k++] = S.top().first;
po[k++] = ' ';
S.pop();
}
}
S.push(make_pair(s[i], prec));
}
else if (s[i] == '(')
parl++;
else if (s[i] == ')')
parl--;
}
while (!S.empty())
{
po[k++] = S.top().first;
po[k++] = ' ';
S.pop();
}
stack<int> O;
for (i = 0; i < strlen(po); i++)
{
if (strchr("1234567890", po[i]) != NULL && po[i] != '\0')
{
x = int(po[i]) - 48;
i++;
while (strchr("+-*/ ", po[i]) == NULL)
{
x = x*10 + int(po[i]) - 48;
i++;
}
O.push(x);
}
else if (po[i] == '+')
{
x1 = O.top();
O.pop();
x2 = O.top();
O.pop();
O.push(x1+x2);
}
else if (po[i] == '-')
{
x1 = O.top();
O.pop();
x2 = O.top();
O.pop();
O.push(x2-x1);
}
else if (po[i] == '*')
{
x1 = O.top();
O.pop();
x2 = O.top();
O.pop();
O.push(x1*x2);
}
else if (po[i] == '/')
{
x1 = O.top();
O.pop();
x2 = O.top();
O.pop();
O.push(x2/x1);
}
}
fout << O.top();
return 0;
}