【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;
   
}

  

posted @ 2015-03-20 02:33  Summer先生  阅读(1285)  评论(0编辑  收藏  举报