后缀表达式

后缀表达式

因为输入的是字符,但是计算的时候有可能是十位及十位以上的数,所以要用到两个栈,一个存储数和操作结束符,另一个也是存储数但是它的作用是用于合成十位及以上数位的数。

#include<bits/stdc++.h>
#define maxn 1001
using namespace std;
char s[1001];
typedef struct stacknode
{
	int top1;
	int top2;
	char data1[maxn];
	char data2[maxn];
}Stack;
Stack st;
void createstack1()
{
	st.top1=-1;
}
void createstack2()
{
	st.top2=-1;
}
int Push1(char x)
{
	st.data1[++st.top1]=x;
}
char Pop1()
{
	return st.data1[st.top1--];
}
int Push2(char y)
{
	st.data2[++st.top2]=y;
}
char Pop2()
{
	return st.data2[st.top2--];
}
int stackEpym()
{
	if(st.top2<=-1)
	return 0;
	else
	return 1;
}
int main()
{
	char p,n,m,m1,n1;
	int len,i;
	int sum=0,l,n2,m2,g;
	createstack1();createstack2();初始话化栈; 
	scanf("%s",s);
	len=strlen(s);
	for(i=0;i<len;i++)
	{
		if((s[i]>='0'&&s[i]<='9')||s[i]=='.')' . ',用于判断十位或十位以上的数 
		{
			Push1(s[i]);
		}
		else if(s[i]=='*'||s[i]=='+'||s[i]=='-'||s[i]=='/')
		{
			if(st.data1[st.top1]=='.') Pop1();///先将操作的结束符' . '给拿出,再进行出栈 
			m2=0;n2=0;
			do
			{
			    m=Pop1();
				Push2(m);
			}while(m!='.');
			if(st.top2!=-1) Pop2();由于当循环结束的时候还是把' . '入栈了 ,所以还要在栈2不为空的时候将' . '出栈; 
			while(stackEpym())
			{
                m1=Pop2();
				m2=m2*10+m1-'0';
			}
			do
			{
			    n=Pop1();
				Push2(n);
			}while(n!='.'&&st.top1>-1);
			if(st.top2!=-1&&st.data2[st.top2]=='.') Pop2();
			while(stackEpym())
			{
				n1=Pop2();
				n2=n2*10+n1-'0';
			}if(st.top1!=-1) Push1('.');/判断是否为空,不为空放置出栈结束符;
			if(s[i]=='*') l=n2*m2;
			else if(s[i]=='+') l=n2+m2;
			else if(s[i]=='-') l=n2-m2;
			else if(s[i]=='/') l=n2/m2;
			sum=l;
			do
			{
				g=l%10;
				p=g+'0';
				l/=10;
				Push2(p);
			}while(l!=0);
			while(stackEpym())
			{
				p=Pop2();
				Push1(p);将计算后的结果重新入栈,用以与后面的数计算; 
			}
			Push1('.');createstack2();
		}
		if(s[i]=='@') break;
	}
	printf("%d ",sum);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值