算法3-4:表达式求值(c++实现)

算数四则运算的规则是

1.先乘除,后加减;

2.从左算到右;

3.先括号内,后括号外。

由此,算式4+2*3-10/5的计算顺序为4+2*3-10/5=4+6-10/5=4+6-2=8。

给定一个以“#”作为结束符的算式,求出算式的结果。

给出严蔚敏《数据结构(C语言)》中的一段算法描述以作参考:

 

 

 下面是一个总结出来用栈来求表达式值的一个口诀:

Input Description

以“#”结尾的表达式,运算数为正整数。每个表达式占一行。

Output Description

输出表达式运算的结果。

Sample Input

4+2*3-10/5#
3*(7-2)#
2*3/2#

Sample Output

8
15
3
#include<iostream>
using namespace std;
#include<stack>
#include<algorithm>
#include<string>

stack<int>num;
stack<char>opera;

void work()
{
	char op = opera.top();//操作符出栈
	int b = num.top();//操作数1出栈
	num.pop();
	int a = num.top();//操作数2出栈
	//注意操作数先出栈的为右操作数
	num.pop();
	int tmp;
	if (op == '+')
	{
		tmp = a + b;
	}
	else if (op == '-')
	{
		tmp = a - b;
	}
	else if (op == '*')
	{
		tmp = a * b;
	}
	else if (op == '/')
	{
		tmp = a / b;
	}
	num.push(tmp);//得到的数据进行入栈
	opera.pop();
}

int bigger(char c)
{
	if (c == '+' || c == '-')
	{
		return 0;
	}
	else if (c == '*' || c == '/')
	{
		return 1;
	}
}
int main()
{
	string a;
	while (cin >> a)
	{
		while (!num.empty())//数字栈不空全部出栈
		{
			num.pop();
		}
		while (!opera.empty())//操作符栈不空全部出栈
		{
			opera.pop();
		}
		int len = a.size();//a的长度
		for (int i = 0; i < len; i++)
		{
			if (a[i] >= '0' && a[i] <= '9')//若为数字123 要将字符'1', '2', '3'转化为整数123
			{
				int tmp = 0;
				while (a[i] >= '0' && a[i] <= '9')
				{
					tmp = tmp * 10 + (a[i] - '0');
					i++;
				}
				num.push(tmp);//转化后的整数入栈
				i--;
			}
			else if (a[i] == '#')//如果为等号直接结束 代表表达式结束了
			{
				break;
			}
			else
			{
				if (opera.empty() || opera.top() == '(')//栈为空 或者栈顶为左括号就直接入栈
				{
					opera.push(a[i]);
				}
				else if (a[i] == ')')//此时为右括号就全部出栈 直到碰见左括号
				{
					while (opera.top() != '(')
					{
						work();
					}
					opera.pop();
				}
				else//栈顶不为右括号的时候
				{
					//只有当栈顶元素符号的优先级大于扫描元素的优先级才出栈(扫描元素的优先级小于等于栈顶元素)
					while (!opera.empty() && opera.top() != '(' && bigger(a[i]) <= bigger(opera.top()))
					{
						work();
					}
					opera.push(a[i]);//扫描元素入栈
				}
			}
			
		}
		while (!opera.empty())
		{
			work();
		}
		cout << num.top() << endl;
	}



	return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值