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

Python体重预测代码运行异常 问题排查与修复求助

体重变化计算代码修复方案

错误定位

  • 类型不匹配:input() 函数返回的是字符串类型,无法直接用于数值运算,需要转换为整数/浮点数类型。
  • 赋值逻辑错误:循环内写的 weight = -4 是直接将体重覆盖为固定值-4,并非在原有体重基础上减去4,不符合体重逐月递减的计算需求。

修正后代码

# 获取用户初始体重,转换为浮点型适配小数体重输入
weight = float(input('What is your starting weight? '))

# 输出6个月的体重变化表
for month in range(1, 7):
    # 每月减去4磅
    weight -= 4
    print('At the end of month', month,
          'your weight will be', weight, 'lbs.')

可选优化方案

如果需要保留初始体重的原始值不被修改,可以单独定义变量存储每月体重:

# 获取用户初始体重
start_weight = float(input('What is your starting weight? '))

# 按月计算体重,不修改初始体重数值
for month in range(1, 7):
    current_weight = start_weight - 4 * month
    print('At the end of month', month,
          'your weight will be', current_weight, 'lbs.')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:30:03