用栈实现一位数的加减乘除,写这个代码
时间: 2024-09-26 14:03:21 浏览: 20
js加减乘除计算器代码.zip
要使用栈实现一位数的加减乘除操作,首先需要理解如何将算术表达式转换成逆波兰表示法(RPN,也称为后缀表达式),这样就方便利用栈的操作了。下面是一个基本的示例,我们将使用Python语言来展示:
```python
class Calculator:
def __init__(self):
self.stack = []
# 加法操作
def add(self, num):
if not self.stack or self.stack[-1] != '-':
self.stack.append(num)
else:
top_num = self.stack.pop()
self.stack.append(top_num + num)
# 减法操作
def subtract(self, num):
if not self.stack or self.stack[-1] != '+':
self.stack.append('-')
self.stack.append(num)
else:
top_num = self.stack.pop()
self.stack.append(top_num - num)
# 乘法操作
def multiply(self, num):
while self.stack and self.stack[-1] != '+' and self.stack[-1] != '-':
multiplicand = self.stack.pop()
multiplier = self.stack.pop()
self.stack.append(multiplier * multiplicand)
self.stack.append(num)
# 除法操作,这里假设整数除法,处理除0的情况需额外检查
def divide(self, num):
divisor = self.stack.pop()
if divisor == 0:
raise ValueError("Cannot divide by zero")
quotient = self.stack.pop() // divisor
self.stack.append(quotient)
# 检查是否运算结束,并返回结果
def result(self):
return self.stack.pop()
# 示例用法
calc = Calculator()
calc.add(5) # [5]
calc.subtract(3) # [2]
calc.multiply(4) # [8]
calc.divide(2) # [4]
try:
calc.result() # 输出 4
except ValueError as e:
print(e) # 如果有除零错误,会在这里打印
阅读全文