这是我正在做的练习: 你已经从麻省理工学院毕业,现在有一份很棒的工作!您搬到旧金山湾区并且 决定你要开始存钱买房子。由于湾区房价非常高, 你意识到你必须存好几年才能付得起首付 房屋付款。在 A 部分中,我们将确定您需要多长时间才能存够足够的钱 鉴于以下假设,用于支付首付的钱:
测试案例1
输入您的年薪:120000, 输入要储蓄的工资百分比(小数形式):0.10, 输入您梦想家园的成本:1000000, 月数:183
测试案例2
输入您的年薪: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}")
我知道我的程序并不包罗万象,但它至少应该解决测试用例 1。 我不知道为什么终端继续运行而没有任何结果。 预先感谢。
它没有给出结果的原因是因为它陷入了 while 循环中。因为
new_total_saving
可能会大于 portion_down_payment
但不等于它(如果它不是 total_saving
的精确倍数),因此循环将永远运行并且从不打印结果。要修复此问题并在保存了 more than portion_down_payment
(而不是 exactly portion_down_payment
)后结束循环,您可以将逻辑不等于 (!=
) 更改为数值不等式 (<
)。