递归---表达式求值

在这里插入图片描述

解题思想:

表达式是个递归的思想

在这里插入图片描述
在这里插入图片描述
意思就是:输入一个表达式,该表达式包含了项,项右包含因子,因子是整数 或 表达式,若是整数则返回整数值,若是表达式则返回下一轮递归的值

补充:

表达式 == 项 + 加减运算符(+、- )
项 == 因子 + 乘除运算符( * 、/ )
因子 == 表达式 + 整数(int 型)

代码:

#include <iostream>
using namespace std;
int factor(); //求一个因子的值
int term(); //求一个项的值
int expression(); //求一个表达式的值

int main() //只能计算整数 
{
	cout << expression() << endl;
	return 0;
}

int expression() //求一个表达式的值
{
	int result = term(); //求第一项的值
	bool more = true; //查看是否只有一个表达式
	while( more)
	{
		char op = cin.peek(); //看一个字符,不取走
		if( op == '+' || op == '-' )
		{
			cin.get(); //从输入中取走一个字符
			int value = term();
			if( op == '+' ) result += value;
			else result -= value;
		}
		else more = false;
	}
	return result;
}

int term() //求一个项的值
{
	int result = factor(); //求第一个因子的值
	while(true)
	{
		char op = cin.peek();
		if( op == '*' || op == '/')
		{
		cin.get();
		int value = factor();
		if( op == '*') result *= value;
		else result /= value;
		}
		else break;
	}
	return result;
}

int factor() //求一个因子的值
{
	int result = 0;
	char c = cin.peek();
	if( c == '(')
	{
		cin.get();
		result = expression();
		cin.get();
	}
	else
	{
		while(isdigit(c))
		{
			result = 10 * result + c - '0';
			cin.get();
			c = cin.peek();
		}
	}
	return result;
}

cin.peek()函数的作用是只看一个字符,不取走

现在我们看一下此题中核心之一的代码:

#include <iostream>
using namespace std;
int main()
{
	int result = 0;
	char c = cin.peek();
	while(isdigit(c))
	{
		result = 10 * result + c - '0';
		cin.get();
		c = cin.peek();
	}
	cout<<result;
	return 0;
}

它的作用是能将输入的字符串中 连续的"数字" 变成 int 型数值,如:

input: 123123
output: 123123

它的作用和 atof() 类似,但因为 atof() 需要输入确定长度的数字字符,而本题中下一个字符是不确定的,下一个字符或许是数字字符、又或许是运算操作符,所以数字字符的长度不能确定,故不能使用 atof()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值