Pagini recente » Cod sursa (job #2961865) | Cod sursa (job #2125734) | Cod sursa (job #303243) | Cod sursa (job #2663858) | Cod sursa (job #1342243)
#include <iostream>
#include <fstream>
using namespace std;
long nr[50000], nrI = -1, opI = -1;
char op[50000];
bool isDigit(char c) {
return ('0' <= c) && (c <= '9');
}
int getPriority(char c)
{
if ((c == '(') || (c == ')')) {
return 1;
} else if ((c == '+') || (c == '-')) {
return 2;
} else if ((c == '*') || (c == '/')) {
return 3;
}
return 0;
}
long doOp(long a, long b, char op) {
if (op == '+') {
return a + b;
} else if (op == '-') {
return a - b;
} else if (op == '*') {
return a * b;
} else if (op == '/') {
return a / b;
}
return 0;
}
void eval()
{
nr[nrI - 1] = doOp(nr[nrI - 1], nr[nrI], op[opI]);
--nrI;
--opI;
}
void dump(char c)
{
cout << "c = " << c << "\n";
cout << "nr: ";
for (int i = 0; i <= nrI; ++i) {
cout << nr[i] << ", ";
}
cout << "\nop: ";
for (int i = 0; i <= opI; ++i) {
cout << op[i] << ", ";
}
cout << "\n\n";
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char old_c = 0, c;
while (fin >> c) {
if (isDigit(c)) {
if (!isDigit(old_c)) {
nr[++nrI] = 0;
}
nr[nrI] = (nr[nrI] * 10) + (c - '0');
} else if (getPriority(c)) {
if (c == '(') {
op[++opI] = '(';
} else if (c == ')') {
while (op[opI] != '(') {
eval();
}
--opI;
} else {
while ((getPriority(c) < getPriority(op[opI])) && (opI > -1)) {
eval();
}
op[++opI] = c;
}
}
old_c = c;
}
while (opI > -1) {
eval();
}
fout << nr[0] << "\n";
return 0;
}