加减乘除实现模板

6 篇文章 0 订阅

加减乘除实现模板:

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

#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;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值