0

假设你有一个投资计划,每年年初投资一定的固定金额。计算去年年底的投资总价值。输入将是每年的投资金额、利率和投资年数。

该程序计算固定年度投资的未来价值。输入年投资额:200 输入年利率:.06 输入年数:12 12年的值为:3576.427533818945

我尝试了一些不同的方法,如下所示,但它没有给我 3576.42,它只给了我 400 美元。有任何想法吗?

principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
    principal = principal * (1+apr)
print("The value in 12 years is: ", principal)
4

3 回答 3

2

如果是年度投资,则应每年添加:

yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))

total = 0
for i in range(years):
    total += yearly
    total *= 1 + apr

print("The value in 12 years is: ", total)

有了你的输入,这个输出

('The value in 12 years is: ', 3576.427533818945)

更新:从评论中回答您的问题,以澄清发生了什么:

1)你可以使用int()foryearly并得到相同的答案,如果你总是投资整数货币,这很好。例如,使用浮点数同样有效,但也允许金额199.99为 。

2)+=并且*=是方便的简写:total += yearly表示total = total + yearly. 它更容易打字,但更重要的是,它更清楚地表达了意思。我是这样读的

for i in range(years): # For each year
    total += yearly    # Grow the total by adding the yearly investment to it
    total *= 1 + apr   # Grow the total by multiplying it by (1 + apr)

较长的形式并不那么清楚:

for i in range(years):        # For each year
    total = total + yearly    # Add total and yearly and assign that to total
    total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total
于 2013-04-18T06:46:55.890 回答
1

它可以解析地完成:

"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)

同样,如果您想弄清楚需要投资的金额以便达到某个数字,您可以执行以下操作:

pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1) 
pmt(1000000, 0.09, 20, 0)

于 2018-05-06T14:39:33.723 回答
0

正如评论中所建议的,你不应该eval()在这里使用。(有关 eval 的更多信息可以在 Python 文档中找到)。-- 相反,更改您的代码以使用float()int()在适用的情况下,如下所示。

此外,您的print()声明打印出括号和逗号,我希望您不想要。我在下面的代码中清理了它,但如果你想要的是你可以随意放回去。

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

# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))

for i in range(years):
    principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal
于 2013-04-18T06:46:05.287 回答