Pagini recente » Cod sursa (job #3264700) | Cod sursa (job #3134273) | Cod sursa (job #399570) | Cod sursa (job #2604439) | Cod sursa (job #3292781)
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack<char> ops;
stack<int> nr;
bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; }
int pri(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return -1;
}
void calc(char op) {
int dr = nr.top();
nr.pop();
int st = nr.top();
if (op == '+') nr.push(st + dr);
if (op == '-')
;
nr.push(st - dr);
if (op == '*') nr.push(st * dr);
if (op == '/') nr.push(st / dr);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
fin >> s;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') continue;
if (s[i] == '(')
ops.push('(');
else if (s[i] == ')') {
while (ops.top() != '(') {
calc(ops.top()), ops.pop();
}
ops.pop();
} else if (isOperator(s[i])) {
while (!ops.empty() && pri(ops.top()) >= pri(s[i])) {
calc(ops.top()), ops.pop();
}
ops.push(s[i]);
} else {
int ac = 0;
while (isdigit(s[i])) ac = ac * 10 + s[i++] - '0';
i--;
}
}
while (!ops.empty()) {
calc(ops.top());
ops.pop();
}
fout << nr.top() << "\n";
fin.close();
fout.close();
return 0;
}