【问题标题】:How can I get an output of a compound interest for every year of the time the amount is invested, using a function and a loop in python?如何使用python中的函数和循环获得投资金额每年的复利输出?
【发布时间】:2021-09-18 12:13:41
【问题描述】:

这是我写的代码,我无法得到预期的结果。 我总是得到一个重复 8 次的数量。

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):
    total = amount * (1+rate)**time
    print(total)

for t in range(time):
    total_new = amount * (1+rate)**time
    print(total_new)

invest(amount, rate, time)

expected outpout for invest(100, 0.05, 8):

year1: $105
year2: $110.25
year3: $115.7625
.
.
.
.
.
year8: $147.745544379

【问题讨论】:

    标签: python loops for-loop logic formula


    【解决方案1】:

    你需要在循环中改变你的变量,把t代替time

            for t in range(1,time):
              total_new = amount * (1+rate)**t
              print(total_new)
    

    【讨论】:

    • 由于我最近在学习,所以处理这段代码对我来说很困难,但你的评论帮助我理解了这段代码的逻辑以及 Gderu 的分析器。谢谢 LiavC 和指挥官 Tvis。!
    【解决方案2】:

    您的功能是正确的,问题仅在您的 for 循环中。 应该是这样的:

    for t in range(time):
        total_new = amount * (1 + rate) ** t
        print(total_new)
    

    您的错误是将所有内容都设置为时间的幂,而不是 t 的幂。变量 t 在变化,而时间保持不变,所以你得到了 8 次相同的结果。

    除此之外,我还建议在 (1 + rate) ** t 周围使用括号,以明确它发生在乘以数量之前。

    【讨论】:

    • 现在我明白了,正如你所说,“时间”的力量是固定的,而“t”正在改变。因此,有必要将“时间”更改为“t”,以便新数量会根据设置为 8 次的“t”获得不同的值。谢谢格德鲁!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-25
    相关资源
    最近更新 更多