首页 > 解决方案 > 对于其中一个测试用例,MIT OCW 问题集 1 的预期输出偏离 1

问题描述

我目前正在做下面列出的 MIT OCW 问题集 1,我几乎已经完成了这个问题,除了我在使用其中一个测试用例的输出时遇到了一些问题。

你已经从麻省理工学院毕业,现在有一份很棒的工作!你搬到旧金山湾区,决定开始存钱买房。由于湾区的房价非常高,你意识到你必须存好几年才能负担得起房子的首付。在 A 部分中,我们将根据以下假设确定您需要多长时间才能节省足够的钱来支付首付:

  1. 将您梦想中的房屋的成本称为total_cost。
  2. 调用预付款part_down_payment所需的费用部分。为简单起见,假设 part_down_payment = 0.25 (25%)。
  3. 调用您迄今为止节省的金额 current_savings。您从当前节省的 0 美元开始。
  4. 假设您明智地投资您当前的储蓄,年回报为 r(换句话说,在每个月底,您会收到额外的 current_savings*r/12 资金用于您的储蓄 - 12 是因为 r 是年率)。假设您的投资获得 r = 0.04 (4%) 的回报。
  5. 假设你的年薪是年薪。
  6. 假设您将每月将一定数额的工资用于储蓄首付。调用那个part_saved。该变量应为十进制形式(即 0.1 表示 10%)。
  7. 在每个月底,您的储蓄将增加您的投资回报,加上您月薪的百分比(年薪/12)。编写一个程序来计算你需要多少个月才能存够首付的钱。你会希望你的主要变量是浮点数,所以你应该将用户输入转换为浮点数。
    1 您的程序应要求用户输入以下变量:
  8. 起薪年薪(annual_salary)
  9. 要保存的工资部分(portion_saved)
  10. 您梦想家园的成本(total_cost)

这是我到目前为止的代码

portion_down_payment = 0.25
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: "))

months = 0
money_saved = 0

while money_saved < (total_cost*portion_down_payment):
    months += 1
    money_saved += annual_salary*portion_saved/12
    interest = (money_saved*r)/12
    money_saved += interest


print(f"Number of months: {months}")

输入的一个测试用例是:120,000 的年薪 0.1 的 part_saved 和 1000000 的 total_cost。预期的输出是

Number of months: 183

但我的代码的实际输出是

Number of months: 182

标签: python

解决方案


您的 while 循环中的顺序是错误的原因。特别是,应该在增加当月的money_saved之前计算利息:

改变这个:

months += 1
money_saved += annual_salary*portion_saved/12
interest = (money_saved*r)/12
money_saved += interest

对此:

months += 1
interest = (money_saved*r)/12
money_saved += annual_salary*portion_saved/12
money_saved += interest

推荐阅读