简单计算器的实现(关于中缀后缀表达式的转化问题--队列和栈的使用)

本文介绍了一种使用队列和栈的数据结构来解析和计算逆波兰表达式的方法。通过将输入字符串转换为逆波兰表示,并利用栈进行计算,实现了表达式的高效求值。文章详细解释了算法流程,包括操作数和运算符的处理,以及优先级比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<iostream>
#include<string>
#include<queue>
#include<stack>
#include<map>
using namespace std;
struct node
{
	double num;
	char op;
	bool flag;
};
queue<node>q;
stack<node>s;
string str;
map<char,int>op;
void change()
{
	node temp;
	for (int i=0;i<str.size();)
	{
		if(str[i]>='0'&&str[i]<='9')
		{
			temp.flag=true;
			temp.num=0;
			while(i<str.length()&&str[i]>='0'&&str[i]<='9')
			{
				temp.num=temp.num*10+(str[i]-'0');
				i++;
			}
			q.push(temp);
		}
		else
		{
			temp.flag=false;
		    while(!s.empty()&&op[str[i]]<=op[s.top().op])
		    {
		       q.push(s.top());
		       s.pop();
			}
			temp.op=str[i];
			s.push(temp);
			i++;
		}
	}
	while(!s.empty())
	{
		q.push(s.top());
		s.pop();
	}
}
double ans()
{
	double temp1,temp2;
	node cur;
	while(!q.empty())
	{
		cur=q.front();
		q.pop();
		if(cur.flag==true)
		{
			s.push(cur);
		}
		else
		{
			temp1=s.top().num;
			s.pop();
			temp2=s.top().num;
			s.pop();
			if(cur.op=='+')temp1+=temp2;
			else if(cur.op=='-')temp1=temp2-temp1;
			else if(cur.op=='*')temp1=1.0*temp1*temp2;
			else temp1=1.0*temp2/temp1;
			cur.flag=true;
			cur.num=temp1;
            s.push(cur);
		}
	}
	return s.top().num;
}
int main()
{
	op['+']=op['-']=1;
    op['*']=op['/']=2;
	getline(cin,str);
	change();
	printf("%lf",ans());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值