带括号的表达式求值(参考算法笔记)

虽然算法原理很简单,但是有几个地方需要注意。
1.因为左括号是要放入操作符栈中的,所以他的优先级要设置为0,不然其他运算符来了,就不知道能不能放进去。
2.栈顶运算符优先级小于op时,才能放入操作符栈。


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

struct node  {
	double num;
	char op;
	bool flag;
};
string str;
stack<node>s;
queue<node>q;
map<char,int>op;
void change() {
	double num;
	node temp;
	for(int i=0;i<str.length();i++) {
        char c=str[i];
		if(c>='0'&&c<='9') {
			temp.flag=true;
			temp.num=c-'0';
			q.push(temp);
		} else {
			
			
			if(c==')') {
				while(!s.empty() &&s.top().op!='(') {
					q.push(s.top());
					s.pop();
				}
				s.pop();
				continue;
			} else if(c!='('){

				while(!s.empty() && op[c]<=op[s.top().op]) {
					q.push(s.top());
					s.pop();
				}

			}temp.flag=false;
			temp.op=c;
			s.push(temp);
		}
	}

	while(!s.empty()){
		q.push(s.top());
		s.pop();
	}//从操作符栈变成了空栈 
}
double cal(){
	double temp1,temp2;
	node cur,temp;
	while(!q.empty()){
		cur=q.front();
		q.pop();
		if(cur.flag==true)s.push(cur);
		 else {
		 	temp2=s.top().num;
		 	s.pop();
		 	temp1=s.top().num;
		 	s.pop();
		 	temp.flag=true;
		 	if(cur.op=='+')temp.num=temp1+temp2;
			if(cur.op=='-')temp.num=temp1-temp2;
			if(cur.op=='*')temp.num=temp1*temp2;
			if(cur.op=='/')temp.num=temp1/temp2;
			s.push(temp);
			  
		 }
	}return s.top().num;
}
int main(int argc, char **argv) {
    op['(']=0;
	op['+']=op['-']=1;
	op['*']=op['/']=2;
	getline(cin,str);
		change();
		printf("%.2f",cal());
	

	return 0;
}


发布了17 篇原创文章 · 获赞 5 · 访问量 2362

猜你喜欢

转载自blog.csdn.net/ilikecarrots/article/details/94554460