1. 程式人生 > >3.1 表示式求值(遞迴實現)

3.1 表示式求值(遞迴實現)

#include<iostream>
#include<cstring>
using namespace std;
int term();
int expr();
int factor();

int expr()
{
	int result = term();
	bool more = true;	
	while(more)
	{
		char c = cin.peek();
		if(c == '+' || c == '-')
		{
			cin.get();
			int value = term();
			if(c == '+')
				result += value;
			else if(c == '-')
				result -= value;
		}
		else more = false; 
	}	
	return result;
}

int term()
{
	int result = factor();
	bool more = true;
	while(more)
	{
		char c = cin.peek();
		if(c == '*' || c == '/')
		{
			cin.get();
			int value = factor();
			if(c == '*')
				result *= value;
			else
				result /= value;
		}
		else
			more = false;
	}
	return result;
}

int factor()
{
	int result = 0;
	char c = cin.peek();
	if(c == '(')
	{
		cin.get();//去掉左括號 
		result = expr();
		cin.get();//去掉右括號 
	}
	else
	{
		while(isdigit(c))
		{
			result = result*10 + c - '0';
			cin.get();
			c = cin.peek() ;
		}
	} 
	return result;
}
int main()
{
	cout << expr() << endl;
	//cout << term() << endl;
//	cout << factor() << endl; 
	return 0;
} 

還有一種方法是通過棧來實現,後面更新~