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

支持 + - * / ^ ()

#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 || 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个 Python 实现,使用四则运算表达式进行求值: ```python # 定义运算符的优先级 precedence = { '+': 1, '-': 1, '*': 2, '/': 2, } def evaluate_expression(expr): # 初始化操作数和运算符 operand_stack = [] operator_stack = [] for token in expr: if token.isdigit(): # 如果是数字,则将其添加到操作数中 operand_stack.append(int(token)) elif token in '+-*/': # 如果是运算符,则将其添加到运算符中 while operator_stack and precedence[operator_stack[-1]] >= precedence[token]: apply_operator(operand_stack, operator_stack) operator_stack.append(token) # 处理剩余的运算符 while operator_stack: apply_operator(operand_stack, operator_stack) # 返回最终结果 return operand_stack.pop() def apply_operator(operand_stack, operator_stack): # 取出运算符和两个操作数 operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() # 根据运算符进行计算,并将结果添加到操作数中 if operator == '+': result = operand1 + operand2 elif operator == '-': result = operand1 - operand2 elif operator == '*': result = operand1 * operand2 elif operator == '/': result = operand1 / operand2 operand_stack.append(result) ``` 这个函数接受一个四则运算表达式,并使用对其进行求值。它首先定义了运算符的优先级,并使用一个操作数和一个运算符来处理表达式。 对于表达式中的每个标记(数字或运算符),它检查该标记的类型。如果是数字,则将其添加到操作数中。如果是运算符,则将其添加到运算符中,并使用 `precedence` 字典来比较其优先级。如果顶的运算符的优先级大于或等于当前运算符的优先级,则从中取出运算符,并应用于操作数的两个操作数,直到顶的运算符的优先级小于当前运算符。 最后,当表达式中的所有标记都处理完后,它会处理剩余的运算符,直到运算符为空。最终,它从操作数中弹出结果,并返回它。 你可以像这样调用这个函数: ```python expr = input("请输入四则运算表达式:") tokens = expr.split() result = evaluate_expression(tokens) print("结果为:", result) ``` 在这个例子中,我们首先接受用户输入的四则运算表达式,并使用 `split()` 函数将其拆分成单独的标记。然后,我们调用 `evaluate_expression()` 函数来对其进行求值,并输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值