繁体   English   中英

为什么这一直循环? 尽管我更新了适当的变量

[英]why does this keep looping? despite me updating the appropriate variables

我多次查看此代码,但我无法弄清楚到底出了什么问题? 此代码应该询问用户输入(房价、年薪、半年加薪、您愿意等待买房的月数),然后输出达到目标数量的最佳储蓄率个月。 储蓄也以 4% 的利率获得利息。 使用二等分搜索。

print('what is the cost of your dream home?')
total_cost=float(input())
print ('what is your annual salary?')
annual_salary=float(input())
portion_down_payment=0.25*total_cost
current_savings=0
print('enter a semi-annual raise, as a decimal')
semi_annual_raise=float(input())

print('in how mnay months do you want to buy your house?')
target_months = int(input())

number_of_months=0
saving_rate=0
first=0
last=10000
steps_in_bisection=0

while target_months != number_of_months:
    saving_rate= int((first+last)/2)
    print ('ok')
    print(number_of_months)
    current_savings=0
    number_of_months=0
    while current_savings < portion_down_payment or current_savings-100< portion_down_payment :
        current_savings += ((saving_rate/10000)*(annual_salary/12))+ (current_savings*0.04)/12
        number_of_months=1+number_of_months
        if number_of_months %6 == 0:
            annual_salary+= semi_annual_raise * annual_salary
       
    
    if number_of_months>target_months:
        first=saving_rate
        steps_in_bisection+=1
        print ('here')
        print(number_of_months)
    elif number_of_months<target_months:
        last=saving_rate
        steps_in_bisection+=1
        print('there') 
        print(number_of_months)
print("best savings rate: ", saving_rate)




print("number of months:",number_of_months)
  1. 将你的代码分解成函数,然后你可以一次测试一个。 在排序的代码中找到问题比在很长的代码中容易得多。

例如,将内循环设为 function,然后将外循环设为 function,这将调用内循环。

  1. 您的外循环条件是不等式:

     while target_months:= number_of_months:

有两个问题:如果值不是整数,它可能会发生,你有非常相似但不完全相等的值,例如:1.0000001 和 1。

或者,该数字可能会跳过该确切值:

x = 5
while x != 0:
    x = x - 2

在此段中,x 的值将是:5, 3, 1, -1, -3, -5, ... 但绝不会为 0,因此外观将永远是 go。

  1. 您在测试其值的循环(外循环)内设置值number_of_months=0

  2. last的值是任意设置为10000的,会不会太小了? 它应该取决于输入的值吗?

好吧,伙计们,我终于想通了。 在第二个 while 循环开始之前,应将年度工资设置回其原始用户输入值。 否则 anuual_salary 将继续增加半年加薪金额,因此,随着年薪不断上涨,越来越低的储蓄率将被接受。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM