Pagini recente » Cod sursa (job #2962185) | Cod sursa (job #2478385) | Cod sursa (job #728339) | Cod sursa (job #3268923) | Cod sursa (job #2756276)
#include <bits/stdc++.h>
#define input "evaluare.in"
#define output "evaluare.out"
using namespace std;
ifstream in(input);
ofstream out(output);
string expresie, polish;
stack < int > stiva, stiva_eval;
int priority_eval(int a)
{
if(a == '+' || a == '-')
return 1;
if(a == '*' || a == '/')
return 2;
return -1;
}
void Read_Compute()
{
in >> expresie;
unsigned L = expresie.size(), i = 0;
while(i < L)
{
if(isdigit(expresie[i]))
{
while(isdigit(expresie[i]))
{
polish.push_back(expresie[i]);
i++;
}
polish.push_back(' ');
}
else if(expresie[i] == '(')
{
stiva.push(expresie[i]);
i++;
}
else if(expresie[i] == ')')
{
while(!stiva.empty() && stiva.top() != '(')
{
polish.push_back(stiva.top());
polish.push_back(' ');
stiva.pop();
}
if(!stiva.empty()) stiva.pop();
i++;
}
else
{
while(!stiva.empty() && priority_eval(stiva.top()) >= priority_eval(expresie[i]))
{
polish.push_back(stiva.top());
polish.push_back(' ');
stiva.pop();
}
stiva.push(expresie[i]);
i++;
}
}
while(!stiva.empty())
{
polish.push_back(stiva.top());
polish.push_back(' ');
stiva.pop();
}
}
bool isoperator(int c)
{
if(c == '+' || c == '-' || c == '*' || c == '/')
return true;
return false;
}
int calculator(int a, int b, int op)
{
if(op == '+')
{
return a + b;
}
else if(op == '*')
{
return a * b;
}
else if(op == '-')
{
return a - b;
}
else if(op == '/')
{
return a / b;
}
}
void Evaluate()
{
unsigned L = polish.size(), i = 0;
while(i < L)
{
if(isdigit(polish[i]))
{
int x = 0;
while(isdigit(polish[i]))
{
x = x * 10 + polish[i] - '0';
i++;
}
stiva_eval.push(x);
}
else if(isoperator(polish[i]))
{
double b = stiva_eval.top(); stiva_eval.pop();
double a = stiva_eval.top(); stiva_eval.pop();
double c = calculator(a, b, polish[i]);
stiva_eval.push(c);
i++;
}
else i++;
}
out << stiva_eval.top();
}
int main()
{
Read_Compute();
Evaluate();
return 0;
}