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

如何用Python函数与循环输出投资期内每一年的复利金额

错误根源

  • 循环计算复利时,幂次固定用了总投资年限time,没有跟着循环变量逐年递增,所以每次计算的都是最终年的总金额,才会重复输出相同数值
  • 你定义的invest函数目前仅能计算最终总收益,没有实现逐年输出的逻辑

修复后代码

amount = float(input('the principal amount: '))
rate = float(input('annual rate of return: '))
time = int(input('how many years it will take: '))

def invest(amount, rate, time):
    for year in range(1, time + 1):
        current_total = amount * (1 + rate) ** year
        print(f"year{year}: ${current_total}")

invest(amount, rate, time)

效果验证

输入本金100、年化收益率0.05、投资期限8年时,输出结果和你给出的预期完全一致,会逐行打印第1到第8年的对应复利金额。

内容的提问来源于stack exchange,提问作者Manuel guevara de la cruz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:24:03