codeup1918 简单计算器

#include<queue>
#include<map>
#include<stack>
#include<algorithm>
#include<string>
#include<iostream>
#include<cstdio>
using namespace std;
struct node{
	double num;
	char op;
	bool flag;
};
string str;
stack<node> o;
queue<node> h;
map<char,int> op;

void change(){
//	double sum;
	node tmp;
	for(int i=0;i<str.size();){
		if(str[i]>='0'&&str[i]<='9'){
			tmp.flag=true;
			tmp.num=str[i++]-'0';//注意这里i要自增!!!! 
			while(i<str.size()&&(str[i]>='0'&&str[i]<='9')){
				tmp.num=tmp.num*10+str[i]-'0';
				i++;
			}
			h.push(tmp);
		}else{
			tmp.flag=false;
			while(!o.empty()&&(op[str[i]]<=op[o.top().op])){
				h.push(o.top());
				o.pop();
			}
			tmp.op=str[i];
			o.push(tmp);
			i++;
		}
	}
		while(!o.empty()){
			h.push(o.top());
			o.pop();
		}
}

double com(){
	double tmp1,tmp2;
	node cur,tmp;
	while(!h.empty()){
		cur=h.front();
		h.pop(); 
		if(cur.flag==true){
			o.push(cur);
		}else{
			tmp2=o.top().num;
			o.pop();
			tmp1=o.top().num;
			o.pop();
			tmp.flag=true;
			if(cur.op=='+') tmp.num=tmp1+tmp2;
			else if(cur.op=='-') tmp.num=tmp1-tmp2;
			else if(cur.op=='*') tmp.num=tmp1*tmp2;
			else tmp.num=tmp1/tmp2;
			o.push(tmp);
		}
	}
	return o.top().num;
}
int main(){
//	int i;//此处千万不能直接定义在循环外面! 
	op['+']=op['-']=1;
	op['*']=op['/']=2;
	while(getline(cin,str),str!="0"){
		for(int i=0;i<str.size();i++){
			if(str[i]==' ')
			str.erase(str.begin()+i);
		}
//		cout<<str;
//cout<<str.size();
	while(!o.empty()) o.pop();//初始化栈!!!!! 
	change();
	printf("%.2f\n",com());
}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值