二、遞歸之表達式求值

代碼轉自郭煒老師講義:

#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 = 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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章