Pagini recente » Cod sursa (job #1876383) | Cod sursa (job #2936018) | Cod sursa (job #2584157) | Cod sursa (job #438754) | Cod sursa (job #2875099)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int prioritate(char op)
{
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
bool operaThor(char c) {
return ( c == '+' || c == '-' || c == '*' || c == '/');
}
bool operand(char c) {
return (c >= '0' && c <= '9') ;
}
int operatie(int a, int b, char op) {
switch(op) {
case '+' : return a + b ;
case '-' : return a - b ;
case '*' : return a * b ;
case '/' : return a / b ;
}
}
int rezolva(string &exp) {
vector <char> operaThori ;
vector <int> operanzi ;
for (int i = 0 ; i < exp.size() ; ++i ) {
char c = exp[i] ;
if (operand(c)) {
int num = 0 ;
while ('0' <= exp[i] && exp[i] <= '9') {
num = num * 10 + exp[i] - '0';
i++;
}
operanzi.push_back(num);
c = exp[i];
}
if ( c == '(' ) {
operaThori.push_back(c) ;
continue ;
}
if ( c == ')' ) {
while(!operaThori.empty()) {
char op = operaThori.back();
operaThori.pop_back();
if ( op == '(' )
break ;
else {
int operand2 = operanzi.back();
operanzi.pop_back();
int operand1 = operanzi.back();
operanzi.pop_back();
operanzi.push_back(operatie(operand1, operand2, op));
}
}
continue;
}
if (operaThor(c)) {
if(operaThori.empty())
operaThori.push_back(c) ;
else {
while (prioritate(operaThori.back()) >= prioritate(c)) {
char op = operaThori.back();
operaThori.pop_back();
int operand2 = operanzi.back();
operanzi.pop_back();
int operand1 = operanzi.back();
operanzi.pop_back();
operanzi.push_back(operatie(operand1, operand2, op));
if(operaThori.empty())
break ;
}
operaThori.push_back(c);
}
}
}
while(!operaThori.empty()){
char op = operaThori.back();
operaThori.pop_back();
int operand2 = operanzi.back();
operanzi.pop_back();
int operand1 = operanzi.back();
operanzi.pop_back();
operanzi.push_back(operatie(operand1, operand2, op));
}
return operanzi.back();
}
int main()
{
string exp ;
fin >> exp ;
fout << rezolva(exp) ;
}