【问题标题】:I have a for loop nested within my while loop, what is causing an infinite loop within my code?我的 while 循环中嵌套了一个 for 循环,是什么导致我的代码中出现无限循环?
【发布时间】: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) &gt; epsilon 将永远是True
  • @Poolka 如何在 while 循环的每次迭代开始时将 current_savings 重置为 0?

标签: python-3.x for-loop if-statement while-loop bisection


【解决方案1】:

您为什么使用 (monthly_salary*portion_saved/10000 ?由于您需要每个月将portion_saved 添加到current_savings,我建议您使用

current_savings+=(current_savings*r/12) + portion_saved

我认为您还可以通过使用以下公式找到要保存的百分比来简化流程

monthly_salary*(save_percent/100)* 36 = down_payment-epsilon

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多