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

使用while循环计算投资翻倍时长返回值远大于预期问题求助

问题根因

代码的bug出在while循环的判断逻辑上:你没有存储初始本金的值,循环条件principal < (2 * principal)只要principal为正数就永远为真——你每次比较的都是当前的本金和它本身的两倍,而不是和初始本金的两倍比较。这就导致循环会一直执行,直到浮点数溢出或者达到精度上限才会停止,所以才会出现输出一万多年的错误结果。

修复方案

你需要提前把初始的本金存到单独的变量里,循环条件改成当前本金 >= 初始本金的两倍时退出,修正后的代码如下:

def main():
    print("This program calculates the amount of time it takes for an investment to double")
    # 存储初始本金
    initial_principal = eval(input("What is the initial investment amount? "))
    apy = eval(input("What is the annual interest rate? "))
    years = 0
    current_principal = initial_principal

    while current_principal < 2 * initial_principal:
        current_principal = current_principal * (1 + apy)
        years = years + 1
    print("It will take", years, "years for your investment to double." )
main()

用你给出的测试用例(本金100、年收益率0.05)运行修正后的代码,输出结果为15年,和预期一致。

  • 补充优化建议:尽量不要用eval()处理用户输入,存在代码注入风险,替换成float(input(...))使用更安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:27:00