用遞歸解決遞歸形式的問題:
表達式求值描述.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;
}