Pagini recente » Cod sursa (job #3290263) | Cod sursa (job #3280164) | Cod sursa (job #2785181) | Cod sursa (job #521598) | Cod sursa (job #3242456)
// indirect recursion
#include <fstream>
#include <string>
int add_sub(const std::string &, int &);
int mult_div(const std::string &, int &);
int factor(const std::string &, int &);
int add_sub(const std::string &expr, int &pos)
{
int result = mult_div(expr, pos);
while (pos < (int)expr.size() && (expr[pos] == '+' || expr[pos] == '-'))
{
int sign = (expr[pos] == '+') ? 1 : -1;
result += sign * mult_div(expr, ++pos);
}
return result;
}
int mult_div(const std::string &expr, int &pos)
{
int result = factor(expr, pos);
while (pos < (int)expr.size() && (expr[pos] == '*' || expr[pos] == '/'))
{
int sign = (expr[pos] == '*') ? 1 : -1;
int next_factor = factor(expr, ++pos);
if (sign == 1)
result *= next_factor;
else
result /= next_factor;
}
return result;
}
int factor(const std::string &expr, int &pos)
{
// a factor can be a number or a parenthesized subexpression
if (expr[pos] == '(')
{
int result = add_sub(expr, ++pos);
++pos;
return result;
}
int number = 0;
while (pos < expr.size() && isdigit(expr[pos]))
{
number = number * 10 + (expr[pos] - '0');
++pos;
}
return number;
}
int main()
{
std::ifstream cin("evaluare.in");
std::ofstream cout("evaluare.out");
std::string expr;
cin >> expr;
int next_unprocessed_position = 0;
cout << add_sub(expr, next_unprocessed_position) << '\n';
return 0;
}