加减乘除实现模板:

只实现了加减乘除四则运算

#include<queue>
#include<stack>
#include<cstdio>
#include<map> 
#include<iostream>
using namespace std;

struct node{
	double num;
	char oper;
	bool if_num;
	node(double num,char oper, bool if_num):num(num),oper(oper),if_num(if_num){}
};



queue<node> que;
stack<node> sta;
map<char,int> map_; 
void init(){
	while(!sta.empty()) sta.pop();
	while(!que.empty()) que.pop();
	
	map_['+'] = 0;
	map_['-'] = 0;
	map_['*'] = 1;
	map_['/'] = 1;
}
//中缀转后缀
void change(string input){
	
	string::iterator it = input.begin();
	for(;it!=input.end();){
		if(*it>= '0' && *it <='9'){
			double num = *it - '0'; it++;
			while(it!=input.end() && *it>= '0' && *it <='9'){
				num = num*10 + (*it - '0');
				it++;
			}
			node temp(num,' ',true);
			que.push(temp);
		}else{
			node temp(0,*it,false); 
//			node temp2 = sta.top();
            //如果是有括号的话,那么遇到左括号‘(’则压入
           // 遇到右括号‘)’则则弹出直到遇到第一个左括号
			while(!sta.empty() && map_[sta.top().oper]>=map_[*it]){
				que.push(sta.top());
				sta.pop();
			}
			sta.push(temp);
			it++;
		} 
	}
		
	while(!sta.empty()){
		que.push(sta.top()); sta.pop();
	}	 
}
//将后缀表达式调出来计算
double cal(){
	
	while(!que.empty()){
		node temp = que.front(); que.pop();
		if(temp.if_num == true){
			sta.push(temp);continue;
		}else{
			node a = sta.top();sta.pop();
			node b = sta.top();sta.pop();
			double ans = 0;
			if(temp.oper == '+'){
				ans = a.num + b.num;
			} else if(temp.oper == '-'){
				ans = b.num - a.num;
			}else if(temp.oper == '*'){
				ans = b.num * a.num;
			}else if(temp.oper == '/'){
				ans = b.num / a.num;
			}
			sta.push(node(ans,' ',true));
		}
	}
	return sta.top().num;
}



int main(){

	char str[100];
	while(gets(str)!=NULL){
		init();
		string input(str);
		string::iterator it = input.begin();
		for(;it!=input.end();){
			if(*it == ' '){
				input.erase(it++);
			}else it++;
		}
		cout<<input<<endl;
		change(input);
		double ans = cal();
		printf("%.3lf\n",ans);
	}
	return 0;
}