栈 表达式求值

把运算的处理专门放在一个函数里,然后通过优先级的判断去调用函数,注意那个’('还是放在else if里面吧,不要和运算混在一起了

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;

stack<int> s1;
stack<char> s2;
int flag=0;

//处理+-*/四个 
map<char,int> cmp={
	{'+',1}, {'-',1} , {'*',2}, {'/',2}
};

void eval(){
	int b=s1.top();s1.pop();
	int a=s1.top();s1.pop();
	char c=s2.top();s2.pop();
	
	int x;
	if(c=='+') x=a+b;
	if(c=='-') x=a-b; 
	if(c=='*') x=a*b;
	if(c=='/'){
		if(b==0) flag=1;
		else x=a/b;
	}
	if(flag) s1.push(0);//随意进一个数
	else s1.push(x);
}



int main(){
	char a[N];
	cin>>a;
	int len=strlen(a);
	
	for(int i=0;i<len;i++){
		//数字 
		int n=0,isnum=0;
		while(i<len && isdigit(a[i])){
			n=n*10+a[i]-'0';
			i++;
			isnum=1;
		}
		if(isnum){
			i--;
			s1.push(n);
		}	
		else if(a[i]=='(') s2.push(a[i]);
		else if(a[i]==')'){
			while(s2.size()&&s2.top()!='(') eval();
			s2.pop();
		}
		else{//
			while(s2.size()&&cmp[s2.top()]>=cmp[a[i]]) eval();
			s2.push(a[i]);
		} 
	}
	//清理低优先级 
	while(s2.size())    eval();
	
	if(flag) cout<<"ILLEGAL"<<endl;
    else cout<<s1.top()<<endl;
	
	return 0;
} 



如果除数是0 的话,直接return 0 吧

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值