Pagini recente » Cod sursa (job #1215733) | Cod sursa (job #328832) | Cod sursa (job #1123399) | Cod sursa (job #2848738) | Cod sursa (job #1199090)
#include <iostream>
#include <cstdio>
#include <stack>
#include <cctype>
using namespace std;
int apply(char op, int x, int y)
{
switch (op) {
case '+': return x+y;
case '-': return x-y;
case '*': return x*y;
case '/': return x/y;
default: return 0;
}
}
void reduce(stack<char>& ops, stack<int>& nums)
{
char op = ops.top();
ops.pop();
int num = nums.top();
nums.pop();
nums.top() = apply(op, nums.top(), num);
}
int main()
{
ios::sync_with_stdio(false);
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
stack<char> ops;
stack<int> nums;
ops.push('(');
bool finish = false;
while (!finish) {
char c;
if (cin.eof()) {
c = ')';
finish = true;
}
else {
c = cin.get();
}
if (isdigit(c)) {
cin.unget();
int num;
cin >> num;
nums.push(num);
}
else {
if (c == '(') {
ops.push(c);
}
else if (c == ')') {
while (ops.top() != '(') {
reduce(ops, nums);
}
ops.pop();
}
else if (c == '+' or c == '-') {
while (ops.top() != '(') {
reduce(ops, nums);
}
ops.push(c);
}
else if (c == '*' or c == '/') {
while (ops.top() == '*' or ops.top() == '/') {
reduce(ops, nums);
}
ops.push(c);
}
}
}
printf("%d\n", nums.top());
return 0;
}