Pagini recente » Cod sursa (job #846035) | Cod sursa (job #846386) | Cod sursa (job #106385) | Cod sursa (job #1711516) | Cod sursa (job #2876118)
#include <iostream>
#include <string>
#include <stack>
#include <cstring>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");#include <iostream>
int precedence(char op){
if(op == '+'||op == '-')
return 1;
if(op == '*'||op == '/')
return 2;
return 0;
}
// Function to perform arithmetic operations.
int applyOp(int a, int b, char op){
switch(op){
case '+':
return a + b;
break;
case '-':
return a - b;
case '*':
return a * b;
break;
case '/':
return a / b;
break;
}
}
int evaluare(string expr){
int i;
stack <int> values;
stack <char> ops;
for(i = 0; i < expr.length(); i++){
if(expr[i] == ' ')
continue;
else if(expr[i] == '('){
ops.push(expr[i]);
}
else if(isdigit(expr[i])){
int val = 0;
while(i < expr.length() &&
isdigit(expr[i]))
{
val = (val*10) + (expr[i]-'0');
i++;
}
values.push(val);
i--;
}
else if(expr[i] == ')')
{
while(!ops.empty() && ops.top() != '(')
{
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
// pop opening brace.
if(!ops.empty())
ops.pop();
}
else
{
while(!ops.empty() && precedence(ops.top())
>= precedence(expr[i])){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
.
ops.push(expr[i]);
}
}
while(!ops.empty()){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
return values.top();
}
int main() {
string s;
fin >> s;
fout << evaluare(expr);
return 0;
}