You need to enable JavaScript to run this app. Python实现的时间计算器计算带小数的速度时输出异常
优惠活动
大模型
产品
解决方案
定价
更多

Python实现的时间计算器计算带小数的速度时输出异常

问题定位与修正方案

核心问题梳理

  • 速度模块类型转换错误:speed()函数中对输入做了int(float(input(...)))的嵌套转换,会直接截断所有小数部分:输入787.5英里时被截断为787,输入3.5小时时被截断为3,最终计算787/3得到262.3333333333333,和实际异常输出完全匹配。
  • 主函数存在冗余错误逻辑:调用完distance()或speed()分支后,代码会继续执行后续重复的距离计算逻辑,其中hours = print(...)写法错误,print仅输出内容、无返回值,会导致后续乘法直接触发类型错误;同时存在拼写偏差(minuets应为minutes)、重复要求用户输入的问题。
  • 距离模块存在同类截断问题:distance()函数中所有输入强制转int,若输入带小数的速度、分钟数,同样会出现计算结果偏差。

修正后代码

def distance():
    # 支持小数输入,避免截断
    mph = float(input('Input how many mph your going at '))
    start = input('Was hours or minutes given? (input hr or min) ')
    if start == "hr":
        hours = float(input('Input hour(s) '))
        e = mph * hours
        print(f'Distance is {e}')
    elif start == "min":
        minutes = float(input('Input minutes '))
        ma = minutes / 60
        ans = ma * mph
        print(f'Distance is {ans}')
    else:
        print('An error has occured. Please restart program')

def speed():
    # 移除多余的int()截断,直接用float接收输入支持小数
    miles = float(input('Input miles '))
    hours = float(input('Input hours '))
    answer = miles / hours
    print(f'The speed is {answer}')


def main():
    question = input('What would you like to find? (type distance, speed, or travel) ')
    if question == "distance":
        distance()
    elif question == "speed":
        speed()
    elif question == "travel":
        print('hi')
    # 移除原代码中分支判断后冗余的错误重复逻辑

main()

验证效果

进入speed功能模块,输入787.5英里、3.5小时,计算结果为225,符合理论预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 08:45:07