Python购房首付储蓄计算程序死循环问题求助
MIT购房首付储蓄计算程序问题排查
问题背景
我正在完成MIT购房首付储蓄计算练习题,需求如下:
- 梦想房屋总价为
total_cost - 首付比例
portion_down_payment=0.25(25%) - 当前储蓄
current_savings初始为0美元 - 储蓄年回报率
r=0.04,每月末收益为current_savings*r/12 - 年薪为
annual_salary - 每月储蓄工资比例
portion_saved(小数形式,如10%为0.1) - 每月末储蓄额增加投资收益+每月工资的对应比例(年薪/12)
程序需获取用户输入的annual_salary、portion_saved、total_cost,输出所需月数。测试用例:
- 输入年薪120000、储蓄比例0.1、房价1000000,输出183个月
- 输入年薪80000、储蓄比例0.15、房价500000,输出105个月
我的代码如下:
#variables and inputs: current_savings=0 r=0.04 additional_current_savings=current_savings*r/12 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=0.25*total_cost monthly_salary=annual_salary / 12 new_total_saving=0 number_of_months=0 total_saving=portion_saved+current_savings+additional_current_savings #a program to calculate how many months it will take someone to save up enough money for a down payment: while new_total_saving != portion_down_payment : new_total_saving += total_saving number_of_months += 1 print(f"Number of months: {number_of_months}")
运行时终端持续运行无输出,请求排查原因并解决。
问题排查与解决
核心问题分析
- 死循环触发原因:
- 循环条件使用
new_total_saving != portion_down_payment,但浮点数运算存在精度误差,new_total_saving几乎不可能完全等于portion_down_payment,导致循环无限执行。 - 每月储蓄额计算逻辑完全错误:
total_saving=portion_saved+current_savings+additional_current_savings没有按照题目要求计算,正确逻辑应为当月工资储蓄部分 + 当前储蓄的月收益,且current_savings需要每月更新。
- 循环条件使用
- 逻辑错误细节:
additional_current_savings初始计算为0后就不再更新,忽略了每月储蓄增长后的收益变化。total_saving直接把储蓄比例数值加进去,而非计算每月工资*储蓄比例。
修正后的代码
current_savings = 0.0 r = 0.04 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 = 0.25 * total_cost monthly_salary = annual_salary / 12 number_of_months = 0 # 循环条件改为储蓄额大于等于首付,避免浮点数精度问题 while current_savings < portion_down_payment: # 计算当月投资收益 investment_income = current_savings * r / 12 # 当月新增储蓄:工资储蓄部分 + 投资收益 current_savings += portion_saved * monthly_salary + investment_income number_of_months += 1 print(f"Number of months: {number_of_months}")
修正说明
- 循环条件改为
current_savings < portion_down_payment,只要储蓄额足够覆盖首付就停止循环,规避浮点数精确匹配的问题。 - 每月更新
current_savings,包含当月工资储蓄和投资收益,严格符合题目中每月末更新储蓄的规则。 - 移除冗余变量,简化代码逻辑,提升可读性。
内容的提问来源于stack exchange,提问作者Oussama El Manar
相关产品推荐
相关产品推荐

