如何用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
相关产品推荐
相关产品推荐

