代码之家  ›  专栏  ›  技术社区  ›  Ari

用于计算住房押金所需储蓄月数的函数

  •  2
  • Ari  · 技术社区  · 6 年前

    完全公开这是一个任务,但我的输出和给定的测试用例之间有一些差异。

    该函数将您的年薪、每月将节省的部分工资作为百分比,以及房屋成本计算在内。

    我想我需要房子总成本的25%。我的工资的一部分每月都花在我的储蓄上,我每个月也从我的储蓄中赚取4%的利息。

    def house_hunting(annual_salary, portion_saved, total_cost):
    
        portion_down_payment = 0.25 * total_cost
        current_savings = 0
        r = 0.04
        months = 0
    
        while current_savings < portion_down_payment:
            current_savings += (annual_salary * portion_saved) / 12
            current_savings += current_savings * r / 12
            months += 1
    
        return months
    
    print( house_hunting(120000,0.1,1000000) )
    print( house_hunting(80000,0.15,500000) )
    

    第一次打电话给我182个月,测试用例显示是183个月。 第二次打电话给我105个月,根据测试案例,这是正确的。

    所以我的数学在某个地方是错的,有人知道我错在哪里吗?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Prune    6 年前

    问题是你给每一笔新存款一个月的利息。相反,你得等到下个月。因此,每个月,你 应该 计算当月余额的利息,以及 然后 交新的定金。很简单,切换这两行:

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

    现在你得到了正确的结果。

        2
  •  2
  •   Jorge Andres Mosquera    6 年前

    就这样修改订单:

    while current_savings < portion_down_payment:
        current_savings += current_savings * r / 12
        current_savings += (annual_salary * portion_saved) / 12
    

    你的储蓄(上个月的活期储蓄)会得到利息,然后再加上新的收入。