前缀表达式的计算

//nyoj 128前缀表达式
#include <iostream>
#include<stdio.h>
#include <sstream>
#include <iomanip>
#include <cstring>
#include <stack>
using namespace std;
char Compare(char c,char d)
{
	switch (c)
	{
	case '+':
	case '-': if(d=='+'||d=='-') return '>'; else return '<';
	case '*':
	case '/':return '>';
	default:
		break;
	}
}
bool IsChar(char c)
{
	if(c=='+'||c=='-'||c=='*'||c=='/')
		return true;
	return false;
}
void Change(char mid[],char post[])
{
	int i=0,j=-1,l=strlen(mid);
	stack<char> s;
	int start,end,flag=0,k,p;
	char temp[20];
	char ch;
	while (i<l)
	{
		if(IsChar(mid[i])||mid[i]==' ')  
		{
			if(flag)  {p=j;j=0; for(k=end;k>=(end-p);k--) mid[k]=temp[j++]; j=-1;flag=0; memset(temp,0,sizeof(temp));} 
			++i;
			continue;
		}
		if((mid[i]>='0'&&mid[i]<='9')||(mid[i]=='.'))
		{
			end=i;
			flag=1;
			temp[++j]=mid[i];
			i++;
		}
	}
	if(flag)  {p=j;j=0; for(k=end;k>=(end-p);k--) mid[k]=temp[j++]; j=-1;flag=0; memset(temp,0,sizeof(temp));}
	//处理完小数点的问题,下面开始转后面表达式
	i=0;
	while(i<l) {s.push(mid[i]);++i;}
	i=0;
	while(i<l) {ch=s.top();s.pop(); post[i++]=ch;}
}

double To(char a[])
{
	stringstream oss;
	oss<<a;
	double result;
	oss>>result;
	return result;
}

double Operator(double a,char  b,double c)
{
	switch (b)
	{
	case '+': return a+c;
	case '-': return a-c;
	case '*': return a*c;
	case '/': return a/c;
	}
}

double run(char post[])
{
	stack<double> s;
	double result,x,y;
	char temp[20];
	memset(temp,0,sizeof(temp));
	int i=0,l=strlen(post),j=-1,flag=0;
	while (i<l)
	{
		if((post[i]>='0'&&post[i]<='9')||(post[i]=='.'))
		{
			temp[++j]=post[i];
			flag=1;
			++i;
		}
		else
		{
			if(flag==1)
			{
				result=To(temp); s.push(result); j=-1;flag=0; memset(temp,0,sizeof(temp));
			}
			if(post[i]==' ') { ++i;continue;}
			else if(IsChar(post[i]))
			{
				x=s.top(); s.pop();
				y=s.top(); s.pop();
				s.push(Operator(x,post[i],y));
				++i;
			}
		}
	}
	return s.top();
}
char mid[1008],post[1008];
int main()
{
	
	while (gets(mid))
	{
	Change(mid,post);
	cout<<setiosflags(ios::fixed)<<setprecision(2)<<run(post)<<endl;
	memset(mid,0,sizeof(mid));
	memset(post,0,sizeof(post));
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值