【PAT】2-3 求前缀表达式的值

求值方法:

对于一个前缀表达式的求值而言,首先要从右至左扫描表达式,从右边第一个字符开始判断,如果当前字符是数字则一直到数字串的末尾再记录下来,如果是运算符,则将右边离得最近的两个“数字串”作相应的运算,以此作为一个新的“数字串”并记录下来。一直扫描到表达式的最左端时,最后运算的值也就是表达式的值。例如,前缀表达式“- 1 + 2 3“的求值,扫描到3时,记录下这个数字串,扫描到2时,记录下这个数字串,当扫描到+时,将+右移做相邻两数字串的运算符,记为2+3,结果为5,记录下这个新数字串,并继续向左扫描,扫描到1时,记录下这个数字串,扫描到-时,将-右移做相邻两数字串的运算符,记为1-5,结果为-4,所以表达式的值为-4。

这里我们用递归的方法解决更为方便。
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#include <set>
#include <sstream>
using namespace std;


#define read() freopen("data.in", "r", stdin)
#define write() freopen("data.out", "w", stdout)
#define rep( i , a , b ) for ( int i = ( a ) ; i <  ( b ) ; ++ i )  
#define For( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i ) 
#define clr( a , x ) memset ( a , x , sizeof a )  
#define cpy( a , x ) memcpy ( a , x , sizeof a ) 
#define _max(a,b) ((a>b)?(a):(b))
#define _min(a,b) ((a<b)?(a):(b))
#define LL long long 


double getOp()
{
	string str;
	cin >> str;
	if (str == "+")
	{
		return getOp()+getOp();
	}else if (str == "-")
	{
		return getOp()-getOp();
	}else if (str == "*")
	{
		return getOp()*getOp();
	}else if (str == "/")
	{
		double x,y;
		x = getOp();
		y = getOp();
		if (fabs(y)<1e-6)
		{
			cout<<"ERROR";
			exit(0);
		}else
		{
			return x/y;
		}
	}else
	{
		double x;
		istringstream istr;
		istr.str(str);
		istr >> x;
		return x; 
	}
}
int main()
{
	read();
	printf("%.1f\n",getOp() );
    return 0;
   
}

  

转载于:https://www.cnblogs.com/acmsummer/p/4352571.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值