栈实现简单的四则运算表达式

这篇博客探讨如何利用栈的数据结构来处理简单的四则运算表达式,包括加、减、乘、除和括号操作。通过栈的压入、弹出操作,实现了表达式的正确运算顺序。

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

支持 + - * / ^ ()

#include<iostream>
#include<cstring>
#include<string>
#include<stack>
#include<cmath>
#include<cstdio>
using namespace std;

stack<int> opnd; //操作数栈
stack<char> optr; //算术符栈
string expression; //存放表达式

//返回两算术符a和b的优先关系
char Compare(char a,char b)
{
	if('#' == a)
	{
		if('#'== b)
			return '=';
		else
			return '<';
	}

	if('+'== a || '-'== a)
	{
		if('*'== b || '/'== b || '^'== b || '('== b)
			return '<';
		else
			return '>';
	}

	if('*'== a || '/'== a)
	{
		if('('== b || '^'== b)
			return '<';
		else
			return '>';
	}

	if('^'== a)
	{
		// 2^3^2 相当于2^(3^2) 
		if('^' == b || '(' == b )
			return '<';
		else
			return '>';
	}

	if('('== a)
	{
		if(')'== b)
			return '=';
		else
			return '<';
	}
}

//返回计算结果
int Calculate(int a,int b,char op)
{
	switch (op)
	{
	case '+':
		return a+b;
	case '-':
		return a-b;
	case '*':
		return a*b;
	case '/':
		return a/b;
	case '^':
		return pow(a,b);
	}
}

//是否是运算符
bool Isoptr(char c)
{
	static string oprator("+-*/^()#");
	//没找到返回 npos
	if(oprator.find(c) == string::npos)
	{
		return false;
	}
	return true;
}

//求值过程
int EvaluateExpression()
{
	int i=0,num=0;
	while ( expression[i]!='#' || optr.top()!='#' )
	{
		if( !Isoptr(expression[i]) )
		{
			//不是算术符,则是操作数
			num=0;
			while( !Isoptr(expression[i]) )
			{
				//求得此操作数
				num *= 10; 
				num += expression[i]-'0';
				++i;
			}
			opnd.push(num);
		}
		else
		{
			//运算符栈顶元素 与 表达式当前的 运算符相比较
			switch (Compare(optr.top(),expression[i] ))
			{
			case '<':
				optr.push(expression[i]);
				++i;
				break;
				//小括号丢掉
			case '=':
				optr.pop();
				++i;
				break;
			case '>':
				int a = opnd.top(); opnd.pop();
				int b = opnd.top(); opnd.pop();
				printf("%d%c%d=%d\n",b,optr.top(),a,Calculate(b,a,optr.top()));
				opnd.push(Calculate(b,a,optr.top())); //注意 a 和 b 的顺序
				optr.pop();
				break;
			}
		}
	}
	optr.push('#');//表达式最左边录入一个 ’#‘,形成一对 '#'
	int res=opnd.top();
	opnd.pop();
	return res;
}

int main()
{
	/*在表达式最左边增加一个'#,'形成一对 '#'
	 同时当表达式输入完后在录入一个’#‘表示结束
	*/
	optr.push('#');
	int count=0;
	while ( cin>>expression )
	{
		int sum=expression.size();
		expression[sum]='#';
		++count;
		cout<<"Case "<<count<<":"<<EvaluateExpression()<<endl;
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值