NYOJ - 35 表达式求值 分类: NYOJ 2015-03-18 10:33 31人阅读 评论(0) 收藏

#include<iostream>
#include<string>
#include<stack>
#include<cstdio>
using namespace std;
stack<double>sn;
stack<char>sc;
	double num, des, dou;
	bool prt, flag;
	int t, len;
	string str;
bool isNum(char c)
{
	if(c >= '0' && c <= '9')
		return true;
	if(c== '.')
	{
		flag = true;
		return true;
	}
	return false;
}

bool isOp(char c)
{
	if(c == '+' || c == '-' || c == '*' || c == '/')
		return true;
	return false;
}

void init()
{
	while(sn.size())	sn.pop();
	while(sc.size())	sc.pop();
	str.clear();
	len = num = des = 0;
	dou = 1;
	prt = false;
	flag = false;
}

void calm()
{
	if(sc.size() && isOp(sc.top()))
	{
		double ans;
		double y = sn.top();
		sn.pop();
		double x = sn.top();
		sn.pop();
		char op = sc.top();
		sc.pop();
		switch(op)
		{
			case '+':	ans = x + y;	break;
			case '-':	ans = x - y;	break;
			case '*':	ans = x * y;	break;
			case '/':	ans = x / y;	break;
		}		
//		cout<<op<<" "<<ans<<endl;
		sn.push(ans);
	}

}

int main()
{
//	freopen("in.in","r",stdin); 
	cin>>t;
	while(t--)
	{
		init();
		cin>>str;
		int len = str.length();
		
		for(int i = 0; i < len; i++)
		{
			if(isNum(str[i]))
			{
				if(str[i] == '.')	continue;
				if(!flag)	num = num*10 + str[i] - '0';
				else{
					des = des*10 + str[i] - '0';
					dou *= 10;
				}
			}
			else
			{
				num = num + des/dou;
				if(str[i] == '+' || str[i] == '-')
				{	
					if(!prt)	sn.push(num);
					while(sc.size() && sc.top() != '(')calm();
					sc.push(str[i]);
					prt = false;
				}
				else if(str[i] == '*' || str[i] == '/')
				{
					if(!prt)	sn.push(num);
					if(sc.size())
						if(sc.top()=='*' || sc.top()=='/')
							calm();
					sc.push(str[i]);
					prt = false;
				}
				else if(str[i] == '(')
				{
					sc.push(str[i]);
				}
				else if(str[i] == ')')
				{
					if(!prt)	sn.push(num);
					while(sc.top() != '(')	calm();
						
					sc.pop();
					prt = true;
				}
				else
				{
					if(!prt)	sn.push(num);
					while(sn.size() > 1)	calm();				
						printf("%0.2lf\n",sn.top());
					sn.pop();
					break;
				}
				num = 0; 
				flag = false;
				dou = 1;
				des = 0;
			}
		}		
	}
	

	return 0;
}        



版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-03-18 10:33  天I火  阅读(129)  评论(0编辑  收藏  举报