简体   繁体   中英

Why is this an infinite loop…? I don't understand

#import time

annual_salary = int(input("Enter your annual salary: "))
monthly_salary = annual_salary / 12
#print(monthly_salary)

portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
monthly_saved = monthly_salary * portion_saved
#print(monthly_saved)

total_cost = int(input("Enter the cost of your dream home: "))
portion_down_payment = total_cost * 0.25
#print(portion_down_payment)

current_savings = 0

number_of_months = 0

while current_savings < portion_down_payment:
    #time.sleep(1)
    current_savings *= 0.04/12
    current_savings += monthly_saved
    number_of_months += 1
    print(current_savings, number_of_months)

print("Number of months:", number_of_months)

Result:

Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
1000.0 1
1003.3333333333334 2
1003.3444444444444 3
1003.3444814814815 4
1003.3444816049383 5
1003.3444816053498 6
1003.3444816053511 7
1003.3444816053511 8
1003.3444816053511 9
1003.3444816053511 10
1003.3444816053511 11
1003.3444816053511 12
1003.3444816053511 13
1003.3444816053511 14
1003.3444816053511 15
1003.3444816053511 16
# Manually Terminated

What is wrong with this code??? I'm so confused... probably something dumb. ab c defghijklmnopq r stuvwxyz

current_savings *= 0.04/12

You're multiplying current_savings by 0.00333333333333333333333333333333 every loop.

If you start with 1: current_savings wlll equal 1 * 0.00333333333333333333333333333333

Again second loop it will get even smaller. You're making current_savings 3% of it's value, it will never be larger than the portion_down_payment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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