# 四则运算表达式求值（递归）

#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
int expression_value();//表达式求值
int term_value();//项求值
int factor_value();//因子求值

int main()
{
cout << expression_value() << endl;
return 0;
}
int expression_value()
{
int result = term_value();
bool next = true;//判断是否有下一项
while (next)
{
char op = cin.peek();//只观测，不取走
if (op == '+' || op == '-')
{
cin.get();//取走
int value = term_value();
if (op == '+')
result += value;
else
result -= value;
}
else
next = false;
}
return result;
}

int term_value()//项求值
{
int result = factor_value();
while (true)
{
char op = cin.peek();//只观测
if (op == '*' || op == '/')
{
cin.get();//取走
int value = factor_value();
if (op == '*')
result *= value;
else
result /= value;
}
else
break;
}
return result;
}

int factor_value()//因子求值
{
char op = cin.peek();
int result = 0;
if (op == '(')
{
cin.get();//取走左括号(
result = expression_value();
cin.get();//取走右括号)
}
else
{
char c = cin.peek();
while (isdigit(c))
{
result = 10 * result + (c - '0');
cin.get();//取走
c = cin.peek();//观测下一个
}
}
return result;

}


08-22 8320

04-09 1327
08-26 7988
08-13 978
03-03 146
10-19 5355
02-26 239