表达式求值(栈)

本文介绍了一种利用两个栈,即操作数栈(OPND)和运算符栈(OPTR),来解析和计算数学表达式的方法。通过定义运算符的优先级,文章详细描述了如何处理括号和不同运算符的顺序,确保表达式的正确计算。

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

用OPTR栈和OPND栈分别来存储运算符和操作数,以‘#’作为结束符号
输入ch,
若是操作数,压入OPND栈。
若是运算符,比较OPTR栈顶元素和ch的比较级关系
OPTR栈顶元素大于ch,弹出OPTR的运算符,从OPND中弹出两 个数,作计算并压入OPND中。
OPTR栈顶元素小于ch,将ch压入OPTR。
若ch为’(‘或’)’,另作比较级处理,方法如下表:

OPTR.top\ch+-*/()
+-1000
*/1101
(0002
)2222

0表示OPTR栈顶元素比较级小于ch
1表示OPTR栈顶元素比较级大于ch
2表示在OPTR中’)‘作为栈顶元素,上一个元素是’(’

比较级计算

int percede(char top,char ch){
	if (top=='+'||top=='-'){
		if(ch=='+'||ch=='-'||ch==')'){
			return 1;
		}
		if (ch=='*'||ch=='/'||ch=='('){
			return 0;
		}
	}
	if (top=='*'||top=='/'){
		if (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch==')'){
			return 1;
		}
		if (ch=='('){
			return 0;
		}
	}
	if (top=='('){
		if (ch==')'){
			return 2;
		}
		else return 0;
	}
	if (top==')'){
		return 2;
	}
}

从键盘输入ch,如果是操作数,需要先转换成int类型,再存入OPND

int chartoint(char ch){
	return int( ch )-48;
}

计算器函数

int cal(char ch,int a,int b){
	if (ch=='+'){
		return a+b;
	}
	if (ch=='-'){
		return a-b;
	}
	if (ch=='*'){
		return a*b;
	}
	if (ch=='/'){
		return a/b;
	}
}

源代码

#include <iostream>
#include <stack>
using namespace std;

int chartoint(char ch){//字符型向整型转换
	return int( ch )-48;
}

int percede(char top,char ch){//优先级关系,1表示top高于ch,0表示top低于ch,2表示top和ch相等
	if (top=='+'||top=='-'){
		if(ch=='+'||ch=='-'||ch==')'){
			return 1;
		}
		if (ch=='*'||ch=='/'||ch=='('){
			return 0;
		}
	}
	if (top=='*'||top=='/'){
		if (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch==')'){
			return 1;
		}
		if (ch=='('){
			return 0;
		}
	}
	if (top=='('){
		if (ch==')'){
			return 2;
		}
		else return 0;
	}
	if (top==')'){
		return 2;
	}
}

int cal(char ch,int a,int b){
	if (ch=='+'){
		return a+b;
	}
	if (ch=='-'){
		return a-b;
	}
	if (ch=='*'){
		return a*b;
	}
	if (ch=='/'){
		return a/b;
	}
}

void main()
{
	char ch;
	int a,b;

	stack < char > OPTR;//运算符栈
	stack < int > OPND;//操作数栈

	cin>>ch;
	while(ch!='#'){//表达式以#截止
		if (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'){//ch是运算符
			if (OPTR.empty()||percede(OPTR.top(),ch)==0){//空栈或top优先级低于ch
				OPTR.push(ch);
			}
			else if (percede(OPTR.top(),ch)==1){//top优先级高于ch
				b=OPND.top();
				OPND.pop();
				a=OPND.top();
				OPND.top()=cal(OPTR.top(),a,b);
				OPTR.top()=ch;
			}
			else if (percede(OPTR.top(),ch)==2){//'('匹配到')'
				OPTR.pop();
				OPTR.top()=ch;
			}
		}
		 else {//ch是操作数
			OPND.push(chartoint(ch));//入栈
		}
		cin>>ch;
	}
	while (!OPTR.empty()){//运算栈中仍有运算符
		if (OPTR.top()==')'){
			OPTR.pop();
			OPTR.pop();
		}
		else {
			b=OPND.top();
			OPND.pop();
			a=OPND.top();
			OPND.top()=cal(OPTR.top(),a,b);
			OPTR.pop();
		}
	}

	cout<<OPND.top();

	system("pause");
}

计算 (3*4+2)+(6/2-1)#
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值