输入字符串表达式S,实现一个基本计算器来计算,并返回计算的值
时间: 2024-10-28 16:15:40 浏览: 11
输入一个字符串表达式,计算其值.rar_字符串表达式_表达式字符串
要实现一个基于字符串表达式的简单计算器,你可以采用递归解析器或者使用现有的库(如Python的`eval()`函数,但这可能会带来安全风险),这里我将提供一个基础的解析方法来处理加减乘除运算。这个示例仅适用于整数运算,并假设输入不会包含非法字符。
```python
def calculate_expression(s):
def apply_operator(operands, operator):
if operator == '+':
return operands[0] + operands[1]
elif operator == '-':
return operands[0] - operands[1]
elif operator == '*':
return operands[0] * operands[1]
elif operator == '/':
# 确保除数不为零
if operands[1] != 0:
return operands[0] / operands[1]
else:
raise ValueError("Division by zero is not allowed.")
def parse_token(token, operators, operands):
if token.isdigit():
operands.append(int(token))
elif token in operators:
if not operands or not operands[-1].isdigit():
raise ValueError("Invalid expression")
operands.append(apply_operator(operands, token))
operands.pop() # 移除刚应用操作符后的数字
# 分割输入字符串并处理每个部分
tokens = s.split()
if len(tokens) < 2:
raise ValueError("Invalid expression (at least one operator needed)")
operators = ['+', '-', '*', '/']
operands = []
for token in tokens:
parse_token(token, operators, operands)
# 最后一个元素应该是结果
if not operands:
raise ValueError("No result found after parsing")
return operands[0]
# 示例
expression = "5 + 3 * 2"
result = calculate_expression(expression)
print(f"Result of {expression}: {result}")
阅读全文