有人可以向我解释为什么这段代码不起作用吗?
Can someone explain to me why doesn't this piece of code work?
annual_salary = int(input("Your annual salary "))
semi_annual_raise = 0.07
r = 0.04
down_payment = 250000
epsilon = 100
low = 0
high = 10000
guess = (high + low)//2
best_saving_rate = (guess/10000)
months = 0
current_savings = 0
steps = 0
while abs(current_savings - down_payment) >= 100:
for i in range(36):
current_savings += best_saving_rate*(annual_salary/12) + (current_savings*r)/12
months +=1
if months%6 == 0:
annual_salary = annual_salary + semi_annual_raise*annual_salary
if current_savings < down_payment:
low = guess
else:
high = guess
steps += 1
guess = (high + low)//2
best_saving_rate = float(guess/10000)
print(steps)
print(best_saving_rate)
print(current_savings)
此代码应该为试图在 36 个月内有足够的钱支付 250000 美元的人找到最佳储蓄率。我使用二分搜索,我认为我在正确的轨道上,但它不会工作。我认为问题是可变的电流节省不会在每次迭代时重新初始化,我不知道如何让它这样做。请帮忙。
为什么您希望在每次迭代时将 current_savings
重置为 0
?您没有在代码中这样做,那么什么会导致这种情况发生呢?同样从代码的外观来看,您也应该将 months
重置为 0
(尽管看起来 for
循环索引变量 i
实际上应该是月份) .
这修复了我看到的明显错误:
while abs(current_savings - down_payment) >= 100:
current_savings = 0 # add this
for month in range(36): # Change this
current_savings += best_saving_rate * (annual_salary / 12) + (current_savings * r) / 12
# months += 1 <-- remove this
if months % 6 == 0:
annual_salary = int(input("Your annual salary "))
semi_annual_raise = 0.07
r = 0.04
down_payment = 250000
epsilon = 100
low = 0
high = 10000
guess = (high + low)//2
best_saving_rate = (guess/10000)
months = 0
current_savings = 0
steps = 0
while abs(current_savings - down_payment) >= 100:
for i in range(36):
current_savings += best_saving_rate*(annual_salary/12) + (current_savings*r)/12
months +=1
if months%6 == 0:
annual_salary = annual_salary + semi_annual_raise*annual_salary
if current_savings < down_payment:
low = guess
else:
high = guess
steps += 1
guess = (high + low)//2
best_saving_rate = float(guess/10000)
print(steps)
print(best_saving_rate)
print(current_savings)
此代码应该为试图在 36 个月内有足够的钱支付 250000 美元的人找到最佳储蓄率。我使用二分搜索,我认为我在正确的轨道上,但它不会工作。我认为问题是可变的电流节省不会在每次迭代时重新初始化,我不知道如何让它这样做。请帮忙。
为什么您希望在每次迭代时将 current_savings
重置为 0
?您没有在代码中这样做,那么什么会导致这种情况发生呢?同样从代码的外观来看,您也应该将 months
重置为 0
(尽管看起来 for
循环索引变量 i
实际上应该是月份) .
这修复了我看到的明显错误:
while abs(current_savings - down_payment) >= 100:
current_savings = 0 # add this
for month in range(36): # Change this
current_savings += best_saving_rate * (annual_salary / 12) + (current_savings * r) / 12
# months += 1 <-- remove this
if months % 6 == 0: