如何循环百分比投资?

时间:2016-02-11 07:38:46

标签: python python-3.x

我正在做这个简单的任务,财务顾问建议投资一个股票基金,保证在未来五年内增加3%。

这是我的代码:

while True:
    investment = float(input('Enter your initial investment: '))
    if 1000 <= investment <= 100000:
        break
    else:
        print("Investment must be between $1,000 and $100,000")


#Annual interest rate 
apr = 3 / 100
amount = investment

for yr in range(5):
    amount = (amount) * (1. + apr)
    print('After {:>2d} year{} you have:   $ {:>10.2f}'.format(yr, 's,' if yr > 1 else ', ', amount))

2 个答案:

答案 0 :(得分:3)

你明白了。唯一的问题是apr运行整数数学。请改用浮点数,因此apr不会舍入为零:

apr = 3.0 / 100.0

通过更改该行,您的程序可能会正常工作

这是整个代码更改(在评论中要求):

while True:
    investment = float(input('Enter your initial investment: '))
    if 1000 <= investment <= 100000:
        break
    else:
        print("Investment must be between $1,000 and $100,000")


#Annual interest rate 
apr = 3.0 / 100.0
amount = investment

for yr in range(5):
    amount = (amount) * (1. + apr)
    print('After {:>2d} year{} you have:   $ {:>10.2f}'.format(yr, 's,' if yr > 1 else ', ', amount))

我得到的输出是:

Enter your initial investment: 1002 
After  0 year,  you have:   $    1032.06
After  1 year,  you have:   $    1063.02
After  2 years, you have:   $    1094.91
After  3 years, you have:   $    1127.76
After  4 years, you have:   $    1161.59

答案 1 :(得分:0)

new_a=1000
yi = .03
for yr in range(1,6):
    new_a = new_a+new_a*yi
    print('After {:>2d} year{} you have:   $ {}'.format(yr, 's,' , new_a))