Pagini recente » Cod sursa (job #387907) | Cod sursa (job #1147958) | Cod sursa (job #2119229) | Cod sursa (job #2464782) | Cod sursa (job #1850327)
#include <cstdio>
#define MAX_S 100000
using namespace std;
char L[MAX_S];
int readNumber(char* &p) {
int n = 0;
for (; *p >= '0' && *p <= '9'; ++p)
n = 10 * n + *p - '0';
return n;
}
/*
* p - the character we're currently on
* l - the type of term we're currently examining:
* - 0 is a sum
* - 1 is a product
* - 2 is either a token (i.e. a number or variable) or a parenthesis
* This function can also be viewed as a multi-purpose function, it's "mode of
* operation" being set by the value of l. This function is thus nothing more
* than the trivial combination of the functionalities of the three functions in
* the indirect recursive implementation.
*/
int eval(char* &p, int l) {
int res = 0;
if (l == 0) { // Compute the sum of product terms
res = eval(p, l + 1);
while (*p == '+' || *p == '-')
switch (*p) {
case '+': res += eval(++p, l + 1); break;
case '-': res -= eval(++p, l + 1); break;
}
++p;
} else if (l == 1) { // Compute the products of tokens (or parentheses) here
res = eval(p, l + 1);
while (*p == '*' || *p == '/')
switch (*p) {
case '*': res *= eval(++p, l + 1); break;
case '/': res /= eval(++p, l + 1); break;
}
} else // Compute the value of a token, which is either a number or a parenthesis
if (*p == '(')
res = eval(++p, 0);
else
res = readNumber(p);
return res;
}
int main() {
FILE *fin = fopen("evaluare.in", "r");
FILE *fout = fopen("evaluare.out", "w");
fgets(L, MAX_S, fin);
char *p = L;
fprintf(fout, "%d", eval(p, 0));
return 0;
}