这个算法比较难想,是把表达式expression看成用+号或-分开
term看成用*号或/号分开
factor看成括号或一个数,形成递归
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
int factor_value(); // 求一个因子的值
int term_value(); // 求一个项的值
int expression_value(); // 求一个表达式的值
int main()
{
cout << expression_value() << endl;
return 0;
}
int expression_value() //求一个表达式的值
{
int result = term_value(); // 求第一项的值
bool more = true;
while (more)
{
char op = cin.peek(); // 看一个字符,不取走
if (op == '+' || op == '-')
{
cin.get(); // 从输入流取走字符
int value = term_value();
if (op == '+')
result += value;
else
result -= value;
}
else
more = false;
}
return result;
}
int term_value() // 求一个项的值
{
int result = factor_value(); // 求一个因子的值
while (true)
{
char op = c