我有一个程序(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()
如果不引入“未来”,我无法完成修改程序。累加器变量。
# 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()
答案 0 :(得分: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
答案 1 :(得分:0)
嗯,您不需要累加器,但您仍需要一个临时变量来保存定期投资的原始值:
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()