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

浮点数计算结果与计算器有偏差,疑受0退出值影响求排查

问题分析与解决

首先明确:你的退出值0没有干扰计算,因为代码里只要输入m或n为0就直接跳出循环,不会执行后续的数值处理逻辑。

你的代码现在有两个关键问题:

  • 逻辑错误:你定义的sum变量每次循环都会被新的n/m覆盖,最后打印的只是最后一组输入的每股价格,根本没计算所有输入项的平均值。
  • 浮点数精度问题:Python里的float是二进制浮点数,像0.1这类十进制数在二进制中无法精确表示,存储和计算时会有微小误差,这会导致结果和计算器(通常用十进制精确计算)出现细微差异。

修正后的代码

推荐用累计总金额和总股数的方式计算,这样能减少浮点数累加带来的误差:

total_shares = 0.0
total_price = 0.0

while True:
    m = float(input("输入股数,输入0退出: "))
    n = float(input("输入总买入价,输入0退出: "))
    if m == 0 or n == 0:
        break
    # 累计总股数和总金额
    total_shares += m
    total_price += n

# 计算平均每股价格,避免除以0的情况
if total_shares > 0:
    avg_price = total_price / total_shares
    print(f"平均每股价格: {avg_price}")
else:
    print("未输入有效数据")

补充说明

如果需要完全避免二进制浮点数的精度误差,可以用Python标准库的decimal模块,它支持十进制浮点数运算:

from decimal import Decimal, getcontext

# 设置计算精度,可根据需求调整
getcontext().prec = 10

total_shares = Decimal(0)
total_price = Decimal(0)

while True:
    m_input = input("输入股数,输入0退出: ")
    n_input = input("输入总买入价,输入0退出: ")
    if m_input == '0' or n_input == '0':
        break
    try:
        m = Decimal(m_input)
        n = Decimal(n_input)
        total_shares += m
        total_price += n
    except ValueError:
        print("请输入有效的数字")

if total_shares > 0:
    avg_price = total_price / total_shares
    print(f"平均每股价格: {avg_price}")
else:
    print("未输入有效数据")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:15:37