三角函数计算器用栈来写、
时间: 2023-08-14 19:02:26 浏览: 41
您可以使用栈来实现三角函数计算器,以下是一个简单的示例代码:
```python
import math
# 定义操作符优先级
priority = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
# 定义操作符和对应的函数
operators = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
'^': lambda a, b: a ** b,
'sin': lambda a: math.sin(a),
'cos': lambda a: math.cos(a),
'tan': lambda a: math.tan(a),
}
def evaluate(expression):
stack = []
tokens = expression.split()
for token in tokens:
if token in operators:
if token in {'sin', 'cos', 'tan'}: # 处理三角函数
stack.append(token)
else:
while stack and stack[-1] in operators and priority[token] <= priority[stack[-1]]:
operator = stack.pop()
if operator in {'sin', 'cos', 'tan'}: # 处理三角函数
operand = stack.pop()
result = operators[operator](operand)
else:
operand2 = stack.pop()
operand1 = stack.pop()
result = operators[operator](operand1, operand2)
stack.append(result)
stack.append(token)
else:
stack.append(float(token))
while stack:
operator = stack.pop()
if operator in {'sin', 'cos', 'tan'}: # 处理三角函数
operand = stack.pop()
result = operators[operator](operand)
else:
operand2 = stack.pop()
operand1 = stack.pop()
result = operators[operator](operand1, operand2)
stack.append(result)
return stack[0]
# 测试
expression = "sin 30 + cos 45 * 2"
result = evaluate(expression)
print(result)
```
以上代码实现了一个简单的三角函数计算器,通过使用栈来处理表达式中的操作符和操作数,最终得出计算结果。在处理三角函数时,将函数名和操作数分别入栈,计算时取出操作数进行计算。