王道——机试指南

计算字符串的结果

#include<iostream>
#include<stack>
#include<string>
#include<sstream>
#include<vector>
#include<stdlib.h>
using namespace std;

int main(){
	//一个字符一个字符的怎么处理
	string s;
	while(getline(cin,s)){
		cout<<"s:"<<s<<endl;
		if(s=="0") return 0;
		stack<float> res;
		vector<string> op;
		vector<float> num;
		istringstream is(s);
		string temp;
		while(is>>temp){
			cout<<"temp:"<<temp<<endl;
			if(temp=="+"||temp=="-"||temp=="*"||temp=="/"){
				op.push_back(temp);
			}
			else{
				
				num.push_back(atof(temp.c_str()));
			}
		}
		if(op.size()==0){
			printf("%.2f\n",num[0]);
			continue;
		}
			
		for(int i=0,j=0;i<op.size()&&j<num.size();){
			if(res.empty()){
				res.push(num[j]);
				++j;
			}
			if(op[i]=="+"){
				res.push(num[j]);
				++j;
				++i;
			}
			else if(op[i]=="-"){
				res.push(-num[j]);
				++j;
				++i;
			}
			else if(op[i]=="*"){
				float temp=res.top();
				res.pop();
				res.push(temp*num[j]);
				++j;
				++i;
			}
			else{
				float temp=res.top();
				res.pop();
				res.push(temp/num[j]);
				++j;
				++i;
			}
		}
		//!!!作用域的问题
		//!!!特别注意!!!对所有的变量都要初始化!!!! 
		//很神奇啊,这里必须要初始化,如果这里不初始化为0的话,每一次的ans就会累加 
		float ans=0;
		while(!res.empty()){
			cout<<"top:"<<res.top()<<endl;
			ans+=res.top();
			res.pop();
		}
		printf("%.2f\n",ans);
	}
} 

这里要注意学习的几个知识点为

1.如何输入带空格的一行字符串

2.如何将字符串按照空格分开

3.如何将字符串转化为int,float,double

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值