栈的应用 之 用算符优先法求表达式的值

输入为表达式,以‘#’结尾
例如:2+3*(33-23) +5/4#


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <stack> 
#include <stdlib.h>
using namespace std;

char ch[10]={'+','-','*','/','(',')','#'};

int compare[7][7]={       //优先级数组 
	1,1,-1,-1,-1,1,1,
	1,1,-1,-1,-1,1,1,
	1,1,1,1,-1,1,1,
	1,1,1,1,-1,1,1,
	-1,-1,-1,-1,-1,0,1,
	1,1,1,1,1,1,1,
	-1,-1,-1,-1,-1,1,0
};

int precede(char a,char b)  //比较a和b两个运算符的有优先级 
{
	int x,y;
	for(int i=0;i<7;i++)
	{
		if(ch[i]==a) x=i;
		if(ch[i]==b) y=i;
	}
	return compare[x][y];
}

int number(char a[],int sum)  //字符串转实数 
{
	int ans=0;
	for(int i=0;i<sum;i++)
	{
		ans+=(a[i]-'0')*pow(10,sum-i-1);
	}
	return ans;
}

int in(char c)                //判断当前运算符是否合法 
{
	if(c=='+' || c=='-' || c=='*' || c=='/' || c=='(' || c==')' || c=='#') return 1;
	else  return 0;
}

double operate(double a,char theta,double b)  //四则运算 
{
	if(theta=='*') return a*b;
	else if(theta=='/') return a/b;
	else if(theta=='+') return a+b;
	else if(theta=='-') return a-b;
}

int main(int argc, char *argv[]) {
	char s[100],mid[100],c;
	stack<char> optr;  optr.push('#');
	stack<double> opnd;
	scanf("%s",s);
	int count=0;
	c=s[count];
	while(c!='#' || optr.top()!='#')
	{
		if(c-'0'>=0 && c-'0'<=9)
		{
			int coun=0;
			while(c-'0'>=0 && c-'0'<=9)
			{
				mid[coun++]=c;   c=s[++count];
			}
			double num=number(mid,coun);
			opnd.push(num);
		}
		else if(in(c))
		{
			switch(precede(optr.top(),c))
			{
				case -1:
				{
					optr.push(c);  c=s[++count];
					break;
				}
				case 0:
				{
					optr.pop();  c=s[++count];
					break;
				}
				case 1:
				{
					char theta=optr.top();  optr.pop();
					double b=opnd.top();    opnd.pop();
					double a=opnd.top();    opnd.pop();
					opnd.push(operate(a,theta,b));
					break;
				}
			}
		}
	}
	printf("%lf\n",opnd.top());
	return 0;
}


  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值