四则运算表达式求值

用递归解决递归形式的问题 例题: 四则运算表达式求值
输入为四则运算表达式,仅由整数、+、-、*、/ 、(、) 组成,没有空格,要求求其值。假设运算符结果都是整数
。"/"结果也是整数

/*
四则运算表达式求值
思路,采取递归定义表达式
1.表达式由项组成 1>可以是一个单独的项 2>可以是项 +- 项
2.项由因子组成 1>可以是一个单独的因子 2>可以是 因子 /* 因子
3.因子可以是一个表达式的项   可以是一个整数 

(2+3)*(5+7)+9/3
63

*/

#include<iostream>

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();	//开始写成了term_value()出错,注意 
		cin.get();
	}
	else
	{
		while(isdigit(c))
		{
			result = 10 * result + c - '0';
			cin.get();
	 		c = cin.peek(); 
		}
	}
	return result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值