如何在以下递归函数中获得所有月份的总利息?这应该模拟信用卡付款。
def creditcard_interest(balance,months,monthly_interest_rate=2.95/100):
if months==1:
return print("The new balance= ",balance)
else:
min_monthly_payment=balance*0.05
balance=balance-min_monthly_payment
interest=balance*monthly_interest_rate
print("Min_monthly_payment for month "+str(months)+'= ', min_monthly_payment)
print("Unpaid balance for month "+str(months)+'= ',balance)
print("Calculated interest for month "+str(months)+'= ',interest)
return creditcard_interest((balance+interest),months-1,)
答案 0 :(得分:-1)
在每次通话时返回时累积兴趣:
return interest + creditcard_interest((balance+interest), months-1, )
顺便说一下,你的第一句话是非法的:你不能返回一份印刷声明。你想用它做什么?看看你的两个分支的语义:第一个返回与余额相关的东西,而另一个显然返回一个利息金额。
我怀疑你需要做的是print
余额,然后是return
兴趣。有点像...
interest=balance*monthly_interest_rate
if months==1:
print("The new balance= ", balance)
return interest
更改后,
print ("Total interest paid", creditcard_interest(1000, 12))
产量
Min_monthly_payment for month 12= 50.0
Unpaid balance for month 12= 950.0
Calculated interest for month 12= 29.500000000000004
Min_monthly_payment for month 11= 48.975
Unpaid balance for month 11= 930.525
Calculated interest for month 11= 28.89525
Min_monthly_payment for month 10= 47.9710125
Unpaid balance for month 10= 911.4492375
Calculated interest for month 10= 28.302897375
Min_monthly_payment for month 9= 46.98760674375001
Unpaid balance for month 9= 892.76452813125
Calculated interest for month 9= 27.722687978812502
Min_monthly_payment for month 8= 46.02436080550313
Unpaid balance for month 8= 874.4628553045594
Calculated interest for month 8= 27.154372875246846
Min_monthly_payment for month 7= 45.080861408990316
Unpaid balance for month 7= 856.5363667708159
Calculated interest for month 7= 26.597708231304285
Min_monthly_payment for month 6= 44.15670375010601
Unpaid balance for month 6= 838.9773712520142
Calculated interest for month 6= 26.05245521256255
Min_monthly_payment for month 5= 43.25149132322884
Unpaid balance for month 5= 821.778335141348
Calculated interest for month 5= 25.518379880705016
Min_monthly_payment for month 4= 42.364835751102646
Unpaid balance for month 4= 804.9318792709503
Calculated interest for month 4= 24.995253093150563
Min_monthly_payment for month 3= 41.49635661820505
Unpaid balance for month 3= 788.4307757458959
Calculated interest for month 3= 24.48285040474098
Min_monthly_payment for month 2= 40.645681307531845
Unpaid balance for month 2= 772.2679448431049
Calculated interest for month 2= 23.980951971443787
The new balance= 796.2488968145487
Total interest paid 23.48934245602919
您仍然需要处理基本情况(结束条件),也许还有一些格式问题,但这解决了主要问题。