7-2 后缀式求值(一位整型操作数版)

#include<bits/stdc++.h>
using namespace std;

stack<int> ans;

int main() 
{
	int n;
	cin >> n;
	while(n --) 
	{
		string s;
		cin >> s;
		
		int num = 0, way = 0;
		bool flag = 0;
		
		for(int i = 0; i < s.size(); i ++) 
		{
			if(s[i] >= '0' && s[i] <= '9') 
			{
				num ++;	
			}
			if(s[i] == '+' || s[i]== '-' ||s[i] == '*' || s[i] == '/') 
			{
				way ++;
			}
		}
		
		if(num - way != 1) 
		{
			cout << "Expression Error!" << endl;
			continue;
		}

		for(int i = 0; i < s.size(); i ++) 
		{
			if (s[i] >= '0' && s[i] <= '9') 
			{
				ans.push(s[i] - '0');
			}

			if (s[i] == '+') 
			{
				int a = ans.top();
				ans.pop();
				int b = ans.top();
				ans.pop();
				ans.push(a + b);
			} 
			
			else if (s[i] == '-') 
			{
				int a = ans.top();
				ans.pop();
				int b = ans.top();
				ans.pop();
				ans.push(b - a);
			}

			else if (s[i] == '*') 
			{
				int a = ans.top();
				ans.pop();
				int b = ans.top();
				ans.pop();
				ans.push(b * a);
			} 
			
			else if (s[i] == '/') 
			{
				int a = ans.top();
				ans.pop();
				int b = ans.top();
				ans.pop();
				if (a) 
				{
					ans.push(b / a);
				}
				else
				{
					cout << "Division By Zero!" << endl;
					flag = 1;
					break;
				} 
			}
		}
		
		if (flag) 
		{
			continue;
		}
		
		cout << ans.top() << endl;
	}
	
	return 0;
}
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
后缀是一种将表达从中缀转换为后缀,并利用栈来计算表达的方法。一位整操作数指的是表达中只有一个数字作为操作数。 算法步骤如下: 1. 初始化一个空栈 2. 从左到右扫描后缀表达的每一项 3. 如果当前项是一个操作数,将其压入栈中 4. 如果当前项是一个运算符,弹出栈顶的两个操作数,进行该运算符的运算,并将结果压入栈中 5. 扫描完成后,栈中剩下的元素即为表达 下面是伪代码实现: ``` function evaluatePostfix(expression): stack = empty stack for each token in expression: if token is an operand: push token onto stack else if token is an operator: operand2 = pop stack operand1 = pop stack result = evaluate expression (operand1, operand2, token) push result onto stack return pop stack function evaluate expression (operand1, operand2, operator): if operator is '+': return operand1 + operand2 else if operator is '-': return operand1 - operand2 else if operator is '*': return operand1 * operand2 else if operator is '/': return operand1 / operand2 ``` 例如,对于后缀表达 "5 3 +",其过程如下: 1. 初始化一个空栈 2. 读入 "5",将其压入栈中 3. 读入 "3",将其压入栈中 4. 读入 "+",弹出栈顶的两个操作数 "3" 和 "5",进行加法运算得到 "8",将其压入栈中 5. 扫描完成后,栈中剩下唯一的元素 "8" 即为表达 因此,该后缀表达为 "8"。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值