*step3_数据结构_ACM数据结构与STL 简单计算器

http://acm.hdu.edu.cn/showproblem.php?pid=1237

带有优先级运算的这种洞悉,记得用栈。

第一遍循环是从左往右进行乘除运算。

第二遍是将加减完成!

#include<iostream>
#include<stack>
#include<sstream>
#include<string>
#include<iomanip>
using namespace std;
int main(){
	string str;
	while(getline(cin,str)&&str!="0"){
		stringstream ss(str);
		double t;char c;		
		stack<double>s1;
		stack<char>s2;
		
		ss>>t;s1.push(t);
		while(ss>>c>>t){
			s2.push(c);
			s1.push(t);
			if(s2.top()=='*'){
				double a=s1.top();s1.pop();
				double b=s1.top();s1.pop();
				s1.push(a*b);
				s2.pop();				
			}else if(s2.top()=='/'){
				double a=s1.top();s1.pop();
				double b=s1.top();s1.pop();
				s1.push(b/a);//使用栈时要特别注意顺序 
				s2.pop();	
			}
		}
		double sum=0;
		while(!s2.empty()){
			double a=s1.top();s1.pop();
			if(s2.top()=='+'){
				sum+=a;
			}else if(s2.top()=='-'){
				sum-=a;
			}
			s2.pop();
		}		
		cout<<setiosflags(ios::fixed)<<setprecision(2)<<sum+s1.top()<<endl;
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值