用递归解决递归形式的问题:

表达式求值描述.png
表达式的定义是递归的:

子表达式.png

项.png

因子.png
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
//读入一个因子,并且返回其值
int factor_value();
//读入一个项,并且返回其值
int term_value();
//读入一个表达式,并且返回其值
int expression_value();
int main(int argc, char *argv[])
{
cout << "the result value is "<<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 = 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()
{
int result = 0;
char c = cin.peek();
if(c == '('){
cin.get();
result = expression_value();
cin.get();
}
else {
while(isdigit(c)){
result = 10*result + c - '0';
cin.get();
c = cin.peek();
}
}
return result;
}
网友评论