【发布时间】:2019-04-22 11:28:38
【问题描述】:
我是 Python 和一般编码的新手。我正在尝试使用带有嵌套 for 循环的 while 循环来计算可以节省的最低工资百分比,该百分比将在 36 个月内达到节省目标。该代码还包括每 6 个月对工资进行半年加薪并将获得的利息应用于储蓄的功能。
当我运行我的代码时,它会导致无限循环,我无法看到是什么原因造成的。
total_cost = 1000000
semi_annual_raise = 0.07
down_payment = 0.25*total_cost
starting_salary = float(input("What is your annual salary?: "))
monthly_salary = starting_salary/12.0
r = 0.04
steps = 0
epsilon = 100
low = 0
high = 10000
portion_saved = (high + low)/2.0
current_savings = 0
raise_counter = 0
while abs(current_savings - down_payment) > epsilon:
current_savings = 0
for months in range(36):
current_savings += (current_savings*r/12) + (monthly_salary*
(portion_saved/10000))
if raise_counter == 6:
monthly_salary += monthly_salary*semi_annual_raise
raise_counter = 0
raise_counter += 1
if current_savings < down_payment:
low = portion_saved
else:
high = portion_saved
portion_saved = (high + low)/2.0
steps += 1
raise_counter = 0
print ("Number of steps =", steps)
print ("Optimal % to save:", portion_saved/10000)
【问题讨论】:
-
current_savings只会上升,down_payment不会改变?在这种情况下,条件abs(current_savings - down_payment) > epsilon将永远是True。 -
@Poolka 如何在 while 循环的每次迭代开始时将 current_savings 重置为 0?
标签: python-3.x for-loop if-statement while-loop bisection