PTA 后缀式求值 (25 分)

我们人类习惯于书写“中缀式”,如 3 + 5 * 2 ,其值为13。 (p.s. 为什么人类习惯中缀式呢?是因为中缀式比后缀式好用么?)
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是: 3 5 2 * +
现在,请对输入的后缀式进行求值。

输入格式:

在一行中输入一个后缀式,运算数运算符之间用空格分隔,运算数长度不超过6位,运算符仅有+ - * / 四种。

输出格式:

在一行中输出后缀式的值,保留一位小数。

输入样例:

3 5.4 2.2 * +

输出样例:

14.9
#include<iostream>
#include<string>
#include<stdlib.h>
#include<stack>
using namespace std;
stack<double>n;
string s;
double temp;
void cac(int opt)
{
	double a = n.top();n.pop();
	double b = n.top();n.pop();
	double temp;
	if (opt == 43)
		temp = b + a;
	else if (opt == 45)
		temp = b - a;
	else if (opt == 42)
		temp = b * a;
	else if (opt == 47)
		temp = b / a;
	n.push(temp);
}
void push()
{
	int j = 0;
	while (j < s.size())
	{
		string s2;
		while (j < s.size() && s[j] != ' ')
			s2 += s[j++];
		j++;
		if (s2.size() == 1 && s2[0] >= 42 && s2[0] < 48)
			cac(s2[0]);
		else
		{
			double num = atof(s2.c_str());
			n.push(num);
		}
	}
}
int main() 
{
	getline(cin, s);
	 push();
	 printf("%.1lf", n.top());
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值