You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python编写遵循运算优先级规则的计算器?

Python计算器四则运算优先级实现方案

问题根因

你的现有代码采用从左到右依次计算的逻辑,遇到运算符就立即结算前序运算结果,没有区分*//(高优先级)和+/-(低优先级)的运算顺序,因此4+3*3会被计算为(4+3)*3=21,不符合四则运算规则。

推荐实现方案(手动处理优先级,无安全风险)

核心逻辑为分层计算:先完成所有高优先级的乘除运算,再统一处理低优先级的加减运算,通过栈存储中间结果实现:

operation = input('Enter equation: ').replace(" ", "")
num_buffer = ""
stack = []
last_op = "+"  # 初始运算符保证第一个数字正常入栈

for char in operation:
    # 收集数字字符,支持多位数和小数
    if char not in ("+", "-", "*", "/"):
        num_buffer += char
    else:
        current_num = float(num_buffer)
        # 根据上一个运算符处理当前数字
        if last_op == "+":
            stack.append(current_num)
        elif last_op == "-":
            stack.append(-current_num)
        elif last_op == "*":
            # 乘除直接和栈顶元素计算,更新栈顶
            stack.append(stack.pop() * current_num)
        elif last_op == "/":
            stack.append(stack.pop() / current_num)
        # 重置状态
        last_op = char
        num_buffer = ""

# 处理最后一个数字
current_num = float(num_buffer)
if last_op == "+":
    stack.append(current_num)
elif last_op == "-":
    stack.append(-current_num)
elif last_op == "*":
    stack.append(stack.pop() * current_num)
elif last_op == "/":
    stack.append(stack.pop() / current_num)

# 栈内元素求和即为最终结果
result = sum(stack)
# 优化整数结果的显示格式
print(int(result) if result.is_integer() else result)

测试效果:输入4+3*3输出13,输入20/2+3*4输出22,均符合运算优先级要求。

快捷方案(仅个人使用可选)

如果仅自己使用不需要考虑输入安全,可以直接调用Python内置的eval函数,它本身支持标准四则运算优先级:

operation = input('Enter equation: ').replace(" ", "")
# 注意:eval会执行任意输入的代码,不可用于有外部用户输入的公开场景
result = eval(operation)
print(int(result) if result.is_integer() else result)

内容的提问来源于stack exchange,提问作者The Vinchi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:15:01