Pagini recente » Istoria paginii utilizator/za_flafi_uan | Cod sursa (job #2321187) | Cod sursa (job #1003500) | Cod sursa (job #1887397) | Cod sursa (job #2962097)
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <cstring>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
int i , n;
char exp[100005];
stack < char > op;
stack <int > num;
int calculate (int val1 , int val2 , char oper)
{
if (oper == '+')
return val1 + val2;
if (oper == '-')
return val1 - val2;
if (oper == '*')
return val1 * val2;
if (oper == '/')
return val1 / val2;
}
int priority (char a)
{
if (a == '+' || a == '-')
return 1;
if (a == '*' || a == '/')
return 2;
return 0;
}
int main()
{
f >> exp;
int n = strlen (exp) - 1;
for (int i = 0 ; i <= n ; i++)
{
if (exp[i] == '(')
op.push ('(');
else
if (isdigit (exp[i]))
{
int val = 0;
while (isdigit (exp[i]) && i <= n)
{
val = val * 10 + (exp[i] - '0');
i++;
}
num.push (val);
i--;
}
else
if (exp[i] == ')')
{
while (op.top () != '(' && op.empty() == 0)
{
char operat = op.top ();
op.pop ();
int num2 = num.top ();
num.pop ();
int num1 = num.top();
num.pop ();
num.push (calculate (num1 , num2 , operat));
}
if (op.empty () == 0)
op.pop ();
}
else
{
while (op.empty () == 0 && priority (op.top ()) >= priority (exp[i]))
{
char operat = op.top ();
op.pop ();
int num2 = num.top ();
num.pop ();
int num1 = num.top ();
num.pop ();
num.push (calculate (num1 , num2 , operat));
}
op.push (exp[i]);
}
}
while (op.empty () == 0)
{
char operat = op.top ();
op.pop ();
int num2 = num.top ();
num.pop ();
int num1 = num.top ();
num.pop ();
num.push (calculate (num1 , num2 , operat));
}
g << num.top ();
return 0;
}