为何计算房屋首付所需月数的Python程序输出始终为0?
问题:Python计算攒首付月数程序始终输出0
我是一名高中生,正在完成OCW课程作业,要写Python程序算攒够房屋首付需要的月数,但运行后输出一直是0,找不到问题出在哪。下面是我的代码、作业要求和测试用例:
我的代码
print("Please enter you starting annual salary: ") annual_salary = float(input()) monthly_salary = annual_salary/12 print("Please enter your portion of salary to be saved: ") portion_saved = float(input()) print ("Please enter the cost of your dream home: ") total_cost = float(input()) current_savings = 0 r = 0.04/12 n = 0 portion_down_payment = total_cost*int(.25) if current_savings < portion_down_payment: monthly_savings = monthly_salary*portion_saved interest = monthly_savings*r current_savings = current_savings + monthly_savings + interest n =+ 1 else: print(n)
作业要求
- 将梦想房屋的成本记为
total_cost - 首付比例记为
portion_down_payment,默认值为0.25(25%) - 当前已攒金额记为
current_savings,初始值为0美元 - 存款年回报率为r,每月末获得
current_savings*r/12的收益(r=0.04即4%) - 年薪为
annual_salary - 每月攒首付的工资比例记为
portion_saved,需以小数形式输入(如10%输入0.1) - 每月末存款增加投资收益+月薪的一定比例(月薪为
annual_salary/12),程序要计算攒够首付的月数,输入需转为浮点数,需请求用户输入起始年薪、每月存款比例、房屋成本
测试用例1
- 输入年薪:120000
- 输入存款比例(小数):0.10
- 输入房屋成本:1000000
- 预期输出月数:183
问题原因及修复方案
几个关键错误点
- 首付计算彻底错误:
int(.25)会把0.25转成整数0,直接导致portion_down_payment变成0,程序一开始就判定已经攒够首付,直接输出0。 - 没有循环执行攒钱逻辑:用
if语句只会判断一次,执行一次存款更新就结束,不会重复执行直到攒够首付。 - 利息计算错误:每月利息应该是当前已有存款产生的收益,也就是
current_savings * r,你用当月存的钱算利息是错的。 - 月数累加错误:
n =+ 1是把n赋值为1,正确的累加应该是n += 1。
修复后的代码
print("Please enter your starting annual salary: ") annual_salary = float(input()) monthly_salary = annual_salary / 12 print("Please enter your portion of salary to be saved: ") portion_saved = float(input()) print("Please enter the cost of your dream home: ") total_cost = float(input()) current_savings = 0.0 monthly_return_rate = 0.04 / 12 months = 0 # 修正首付计算,去掉多余的int转换 portion_down_payment = total_cost * 0.25 # 用while循环持续执行直到攒够首付 while current_savings < portion_down_payment: # 当月利息:当前存款的月收益 monthly_interest = current_savings * monthly_return_rate # 当月存入的工资部分 monthly_saved = monthly_salary * portion_saved # 更新存款总额 current_savings += monthly_saved + monthly_interest # 月数加1 months += 1 # 循环结束后输出结果 print(months)
验证结果
用测试用例1的输入运行修复后的代码,输出为183,符合预期要求。
内容的提问来源于stack exchange,提问作者codinggirl123
相关产品推荐
相关产品推荐

