【问题标题】:Python - Accumulated Value of Annual InvestmentPython - 年度投资累计值
【发布时间】:2016-11-11 13:14:55
【问题描述】:

我有一个程序 (futval.py) 可以计算 10 年后的投资价值。我想修改程序,以便在 10 年后计算一次投资的价值,而不是计算一次投资的价值,而是在 10 年后计算每年投资的价值。我想在不使用累加器变量的情况下做到这一点。是否可以仅使用原始程序中存在的变量(投资,apr,i)来执行此操作?

# futval.py
# A program to compute the value of an investment
# carried 10 years into the future

def main():
    print "This program calculates the future value",
    print "of a 10-year investment."

    investment = input("Enter the initial investment: ")
    apr = input("Enter the annual interest rate: ")

    for i in range(10):
        investment = investment * (1 + apr)

    print "The value in 10 years is:", investment

main()

如果不引入“futval”累加器变量,我无法完成对程序的修改。

# futval10.py
# A program to compute the value of an annual investment
# carried 10 years into the future

def main():
    print "This program calculates the future value",
    print "of a 10-year annual investment."

    investment = input("Enter the annual investment: ")
    apr = input("Enter the annual interest rate: ")

    futval = 0

    for i in range(10):
        futval = (futval + investment) * (1+apr)

    print "The value in 10 years is:", futval

main()

【问题讨论】:

  • 你为什么要这样做
  • 这是我正在使用的 Python 教科书中的一个问题。据说,可以在不引入累加器变量的情况下做到这一点,但我不知道怎么做。
  • 我很确定它会是 futval = (investment*10)((1+apr)**10)
  • @Natecat 如果他在第一年年初投资 10 次就对了。

标签: python python-2.3


【解决方案1】:

好的,如果您尝试做一些数学运算,您将自己看到解决方案。第一年我们有:

new_value = investment*(1 + apr)

第二个:

new_second_value = (new_value + investment)*(1+apr)

new_second_value = (investment*(1 + apr) + investment)*(1+apr)

等等。如果你真的尝试将这些东西相乘,你会发现 10 年后的最终值是

investment*((1+apr)**10) + investment*((1+apr)**9)+...   etc

所以你的问题的解决方案就是

print("The value in 10 years is:", sum([investment*((1+apr)**i) for i in range(1, 11)]))

编辑:不知何故,我设法忽略了我写的只是一个几何级数的事实,所以答案更简单:

ten_years_annual_investment = investment*(apr+1)*((apr+1)**10 - 1)/apr

【讨论】:

    【解决方案2】:

    好吧,你不需要累加器,但你仍然需要一个临时变量来保存周期性投资的原始值:

    def main():
        print "This program calculates the future value",
        print "of a 10-year investment."
    
        investment = input("Enter the initial investment: ")
        apr = input("Enter the annual interest rate: ")
    
        hold = investment
        investment = investment / apr
    
        for i in range(10):
            investment = investment * (1 + apr)
    
        investment = investment - hold / apr
    
        print "The value in 10 years is:", investment
    
    main()
    

    【讨论】:

    • 所以这个家伙问“是否可以仅使用原始程序中存在的变量(投资,apr,i)来执行此操作?”你的答案是“添加一个额外的变量”?那是……粗体。
    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    相关资源
    最近更新 更多