我是新的python,我将非常感谢,如果有人能帮我找到我的代码中的错误。谢谢你提前。
这个问题要求我们找到一个最佳储蓄率,以在36个月内支付一套房子的首付款。由于准确地达到这个目标是一个挑战,答案只需要在所需首付款的100美元以内。
为了简化问题,假设:
1.你的半年加薪是0.07(7%)
1.您的投资年回报率为0.04(4%)
1.首付款是房价的0.25(25
1.你存钱买房子的费用是100万美元。
下面是我的原始代码:
annual_salary=float(input("Enter your annual salary:"))
semi_annual_raise=0.07
total_cost=1000000
portion_down_payment = 0.25
current_saving=0
r=0.04
low=0
high=10000
guess=(low+high)/2
numGuesses=0
while abs(portion_down_payment*total_cost-current_saving)>=100:
current_saving=0
portion_saved=guess/10000
for i in range (36):
current_saving+=current_saving*r/12+annual_salary/12*portion_saved
if i%6==0 and i>0:
annual_salary+=annual_salary*semi_annual_raise
if portion_down_payment*total_cost-current_saving>0:
low=guess
else:
high=guess
guess=(low+high)/2
numGuesses+=1
if numGuesses > 1000:
break
if numGuesses>1000:
print("It is not possible to pay the down payment in three years.")
else:
rate=guess/10000
print("steps in bisection search is",numGuesses,"and the best saving rate is",rate)
当输入150000作为annual_salary时,结果为:
It is not possible to pay the down payment in three years.
因为它不会返回正确的答案,我使用了一个函数来计算curring节省,代码如下所示:
annual_salary=float(input("Enter your annual salary:"))
semi_annual_raise=0.07
total_cost=1000000
portion_down_payment = 0.25
r=0.04
low=0
high=10000
guess=(low+high)/2
numGuesses=0
def current_saving(annual_salary,guess,months):
portion_saved=guess/10000
saving=0
r=0.04
semi_annual_raise=0.07
for i in range (months):
saving+=saving*r/12+annual_salary/12*portion_saved
if i%6==0 and i>0:
annual_salary+=annual_salary*semi_annual_raise
return(saving)
total=0
while abs(portion_down_payment*total_cost-total)>=100:
total=current_saving(annual_salary,guess,36)
if portion_down_payment*total_cost-total>0:
low=guess
else:
high=guess
guess=(low+high)/2
numGuesses+=1
if numGuesses > 1000:
break
if numGuesses>1000:
print("It is not possible to pay the down payment in three years.")
else:
rate=guess/10000
print("steps in bisection search is",numGuesses,"and the best saving rate is",rate)
当这次输入150000作为annual_salary时,结果是:
steps in bisection search is 7 and the best saving rate is 0.44140625
我觉得这两个版本基本上做同样的事情,为什么第一个不能工作,但第二个可以呢?我假设while循环中有什么错误,但我不能确定我的错误。再次感谢您的帮助!
1条答案
按热度按时间u0sqgete1#
在不起作用的版本中,不需要在while循环的每次迭代中重置
annual_salary
。在有效的版本
annual_salary
中,每次调用方法时都会重置局部变量。让坏掉的那台机器运转起来