蓝桥杯算法训练 表达式计算

#include <cmath>
#include <cstdio>
#include <algorithm>
#include <stack> 
#include <iostream>
#include <cstring>
using namespace std;

char str[105];
int i=0;
/*
int priority(char x,char y)		//这个函数是错误的,原因在于编译器不能识别 这个表达式(y='(') 
{								//它把最后一个 ) 与第二个 (  匹配了,而我们认为第二个 ( 是一个字符 
								//也就是括号匹配总是寻找邻近的 
	if(x=='+'||x=='-'&&(y=='*'||y=='(' )||y=='/' ))
		return -1;
	else if(x=='+'||x=='-'&&(y=='+'||y=='-'||y==')'||y=='#'))
		return 1;
	if(x=='*'||x=='/'&&(y=='('))
		return -1;
	if(x=='*'||x=='/'&&(y=='+'||y=='-'||y=='*'||y=='/'||y==')'||y=='#'))
		return 1;
	if(x=='('&&(y=='+'||y=='-'||y=='*'||y=='/'||y=='('))
		return -1;
	if(x=='('&&y==')')
		return 0;
	if(x==')')
		return 1;
	if(x=='#'&&(y=='+'||y=='-'||y=='*'||y=='/'||y=='('))
		return -1;
	if(x=='#'&&y=='#')
		return 0;
}
*/
int priority(char x,char y)	
{							//栈顶x,与当前扫描到y比较优先权 
							//栈顶小,返回-1   相等,返回0  大于返回1 
	switch(x)
	{
		case '+':
			if(y=='+'||y=='-'||y==')'||y=='#')
				return 1;
			else
				return -1;
		case '-':
			if(y=='+'||y=='-'||y==')'||y=='#')
				return 1;
			else
				return -1;
		case '*':
			if(y=='(')
				return -1;
			else
				return 1;
		case '/':
			if(y=='(')
				return -1;
			else
				return 1;
		case '(':
			if(y==')')
				return 0;
			else
				return -1;
		case ')':
			return 1; //如果表达式是合法的,')'不可能入栈,这种情况不会发生
		case '#':
			if(y=='#')
				return 0;
			else
				return -1; 
	} 
}

int compute(int left,char op,int right)
{
	if(op=='+')	return left+right;
	if(op=='-') return left-right;
	if(op=='*') return left*right;
	if(op=='/')	return left/right;
}

int main()
{
	stack<int>  stk1;
	stack<char> stk2;
	scanf("%s",str);
	char strr[2]="#";
	strcat(str,strr);
	stk2.push('#');
	while(str[i]!='\0')
	{
		int x=0;
		while(str[i]>='0'&&str[i]<='9')
		{
			x=x*10+str[i]-'0';
			i++;
		}
		if(x!=0)		//输入不能输入0+5这种不合法的数据 
			stk1.push(x);
		if(priority(stk2.top(),str[i])==-1)
			stk2.push(str[i]);
		else if(priority(stk2.top(),str[i])==0)
			stk2.pop();
		else
			{
				while(priority(stk2.top(),str[i])==1)
				{
					char op=stk2.top();stk2.pop();
					int y=stk1.top();stk1.pop();
					int x=stk1.top();stk1.pop();
					stk1.push(compute(x,op,y));
				}
				if(priority(stk2.top(),str[i])==0)
					stk2.pop();
				else
					stk2.push(str[i]);
				
			}
		i++;
			
	}
	int res=stk1.top();
	cout<<res<<endl;
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值