基于链栈结构实现一个简单计算器的功能,支持基本四则运算,求余,括号,次幂 运算等基本操作;还有sin,cos,tan,sqrt等功能
时间: 2023-05-26 16:06:21 浏览: 44
请问您需要Python代码还是其他语言的代码呢?下面是Python代码的实现:
```python
# 定义链栈的结点
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# 定义链栈
class Stack:
def __init__(self):
self.top = None
# 判断栈是否为空
def is_empty(self):
return self.top is None
# 入栈操作
def push(self, data):
new_node = Node(data)
new_node.next = self.top
self.top = new_node
# 出栈操作
def pop(self):
if self.is_empty():
return None
else:
data = self.top.data
self.top = self.top.next
return data
# 返回栈顶元素
def peek(self):
if self.is_empty():
return None
else:
return self.top.data
# 计算表达式的值
def calculate(self, expression):
num_stack = Stack() # 存放数字的栈
op_stack = Stack() # 存放运算符的栈
for token in expression:
if token.isdigit():
num_stack.push(float(token))
elif token in ["sin", "cos", "tan", "sqrt"]:
op_stack.push(token)
elif token == "(":
op_stack.push(token)
elif token == ")":
while op_stack.peek() != "(":
self.apply_operator(num_stack, op_stack)
op_stack.pop()
elif token in ["+", "-", "*", "/", "%", "**"]:
while not op_stack.is_empty() and self.precedence(op_stack.peek()) >= self.precedence(token):
self.apply_operator(num_stack, op_stack)
op_stack.push(token)
while not op_stack.is_empty():
self.apply_operator(num_stack, op_stack)
return num_stack.pop()
# 判断运算符的优先级
def precedence(self, op):
if op in ["sin", "cos", "tan", "sqrt"]:
return 4
elif op == "**":
return 3
elif op in ["*", "/", "%"]:
return 2
elif op in ["+", "-"]:
return 1
else:
return 0
# 应用运算符
def apply_operator(self, num_stack, op_stack):
operator = op_stack.pop()
if operator in ["sin", "cos", "tan", "sqrt"]:
operand = num_stack.pop()
if operator == "sin":
result = round(math.sin(math.radians(operand)), 2)
elif operator == "cos":
result = round(math.cos(math.radians(operand)), 2)
elif operator == "tan":
result = round(math.tan(math.radians(operand)), 2)
elif operator == "sqrt":
result = round(math.sqrt(operand), 2)
num_stack.push(result)
else:
operand2 = num_stack.pop()
operand1 = num_stack.pop()
if operator == "+":
result = operand1 + operand2
elif operator == "-":
result = operand1 - operand2
elif operator == "*":
result = operand1 * operand2
elif operator == "/":
result = operand1 / operand2
elif operator == "%":
result = operand1 % operand2
elif operator == "**":
result = operand1 ** operand2
num_stack.push(result)
if __name__ == "__main__":
s = Stack()
expression = input("请输入表达式:")
result = s.calculate(expression.split())
print("计算结果为:", result)
```
使用示例:
```
请输入表达式:( 23 + sqrt 25 ) / 5 - sin 30
计算结果为: -0.6
```