簡體   English   中英

Python 程序掛起,不知道為什么

[英]Python program hangs, can't figure out why

所以我正在嘗試運行這個相當簡單的程序,它會告訴你考慮到這個人的年薪、要儲蓄的薪水百分比以及總成本,需要多少個月才能支付房屋的首付房子,這里的代碼:

annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))

portion_down_payment = total_cost * 0.25
current_savings = 0.0
monthly_salary = annual_salary / 12
percentage_of_monthly = monthly_salary * portion_saved

months = 0
while current_savings != portion_down_payment:
    current_savings += percentage_of_monthly
    investment_return = current_savings*0.04 / 12
    current_savings += investment_return
    months += 1

print("Number of months:", months)

I've done Python programming before and I am fairly familiar with Java, but I'm a wee bit rusty with Python so I can't figure out why this is happening, here's the output:

運行時代碼 output

如您所見,在輸入“夢想之家”的總成本后,代碼沒有做任何事情,但是,它也沒有提供錯誤消息。 作為一個固執的人,我猜它可能是 IDE,它不是因為我在 Spyder 和命令提示符中嘗試了相同的程序,但仍然沒有運氣

您的 while 語句卡在循環中-

while current_savings != portion_down_payment:

您正在那里進行直接匹配 - 如果它小於或大於它將繼續,則循環僅在 current_savings 完全等於 part_down_payment 時停止。 這種情況發生的可能性非常小,尤其是在處理浮點數時。

將其設置為while current_savings < portion_down_payment應該可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM