波兰表达式 c++

题目描述

波兰表达式是一种把运算符前置的算术表达式,例如普通的表达式2 + 3的波兰表示法为+ 2 3。

波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如(2 + 3) * 4的波兰表示法为* + 2 3 4。

本题求解波兰表达式的值,其中运算符包括+ - * /四个。

输入格式

输入为一行,其中运算符和运算数之间都用空格分隔,运算数是浮点数。

输出格式

输出为一行,表达式的值。

可直接用printf("%f\n", v)输出表达式的值v。

输入输出样列

输入样例1:复制

 
* + 11.0 12.0 + 24.0 35.0

输出样例1:复制

 
1357.000000

说明

可使用atof(str)把字符串转换为一个double类型的浮点数。

atof定义在cstdlib中。

数据保证输入的运算符和运算数,总个数不超过10000个 

【耗时限制】1000ms 【内存限制】64MB

#include<iostream>
#include<stdio.h>
#include<cmath>
#include<sstream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<string>
#include<cstdio>
#include<vector>
#include<deque>
#include<queue>
using namespace std;
string s[10005];
stack <double> num;
void js(string op){
	double l=num.top();num.pop();
	double r=num.top();num.pop();
	if(op=="+"){
		num.push(l+r);
	}
	if(op=="-"){
		num.push(l-r);
	}
	if(op=="*"){
		num.push(l*r);
	}
	if(op=="/"){
		num.push(l/r);
	}
}
int main(){
	int t=1;
	while(cin>>s[t]){
		t++;
	}
	t--;
	for(int i=t;i>=1;i--){
		if(s[i][0]>='0'&& s[i][0]<='9'){
			double x;
			stringstream sin;
			sin<<s[i];
			sin>>x;
			num.push(x);	
		}
		else{
			js(s[i]);
		}
	}
	printf("%f\n",num.top());
	//cout<<num.top();
	return 0;
}

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值