四则运算表达式求值普通代码
时间: 2024-09-30 17:12:54 浏览: 32
java中实现四则运算代码
四则运算表达式的求值通常涉及到基本的算术操作,比如加法、减法、乘法和除法。下面是一个简单的Python代码示例,它使用递归解析器来计算字符串形式的四则运算表达式:
```python
def evaluate_expression(expression):
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
left = values.pop()
if operator == '+':
return left + right
elif operator == '-':
return left - right
elif operator == '*':
return left * right
elif operator == '/':
return int(left) / int(right) # 确保结果是整数
def greater_precedence(op1, op2):
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
return precedence[op1] > precedence[op2]
operators = []
values = []
i = 0
while i < len(expression):
if expression[i].isdigit():
j = i
while j < len(expression) and expression[j].isdigit():
j += 1
values.append(int(expression[i:j]))
i = j
else:
if i > 0 and expression[i-1] != ' ':
operators.append(expression[i])
i += 1
while operators:
op = operators[0]
if not operators or not greater_precedence(op, operators[0]):
values.append(apply_operator(operators, values))
else:
operators.insert(0, op)
return values[-1]
# 示例
expression = "3 + 5 * 2"
result = evaluate_expression(expression)
print(f"表达式 {expression} 的结果是:{result}")
阅读全文