问题描述
我有一个问题,问用户输入以下内容后,我会要求我计算帐户的利率:
P is the present value of the account.
i is the monthly interest rate.
t is the number of months.
我当前拥有的代码是这样:
def get_value(p,i,t):
return p * (1 + i) ** t
def main():
p = float(input("Please enter the current amount of money in your account: "))
i = float(input("Please enter the monthly interest rate: "))
t = float(input("Please enter the number of months: "))
#the while loop would probably go here,but I just dont kNow how to do it#
future_total = get_value(p,t)
print ("\nAfter",t,"months,you will have $",format(future_total,".2f"),"in your account.")
main()
但是输出只给我10个月后的最终金额,如何执行循环以查看自第1个月以来帐户中有多少钱?
解决方法
我首先要创建一个名为month的变量并将其设置为1。然后使用while循环,以便当月份小于输入的月份时,将根据输入的信息更新当前值。这将打印出帐户中每个月的金额,而不仅仅是最终值。
def get_value(p,i,t):
month = 1
while month <= t:
p = p * (1 + i)
print(month,p)
month += 1
def main():
p = float(input("Please enter the current amount of money in your account: "))
i = float(input("Please enter the monthly interest rate: "))
t = float(input("Please enter the number of months: "))
print(get_value(p,t))
# future_total = get_value(p,t)
# print ("\nAfter",t,"months,you will have $",format(future_total,".2f"),"in your account.")
# print(f'After {t} months,you will have ${future_total} in your account.')
main()