计算保存房屋预付款所需的月数

时间:2017-05-03 01:09:09

标签: python

编写一个程序来计算需要多少个月才能节省足够的钱来支付首期款项。像以前一样,假设您的投资获得r = 0.04(或4%)的回报率 所需的首付百分比是0.25(或25%)。让用户输入以下变量:

  1. 起始年薪(annual_salary)
  2. 要保存的工资百分比(part_saved)
  3. 梦想家园的成本(total_cost)
  4. 每半年加薪(semi_annual_raise)em
  5. 这应该是正确的结果: 但是我的程序通过了第一次测试,但在其他两个测试中关闭了一个月,我找不到解决方案

    测试案例1

    Enter your starting annual salary: 120000
    Enter the percent of your salary to save, as a decimal: .05
    Enter the cost of your dream home: 500000
    Enter the semi­annual raise, as a decimal: .03
    Number of months: 142 
    

    测试案例2

    Enter your starting annual salary: 80000
    Enter the percent of your salary to save, as a decimal: .1
    Enter the cost of your dream home: 800000
    Enter the semi­annual raise, as a decimal: .03
    Number of months: 159 
    

    测试案例3

    Enter your starting annual salary: 75000
    Enter the percent of your salary to save, as a decimal: .05
    Enter the cost of your dream home: 1500000
    Enter the semi­annual raise, as a decimal: .05
    Number of months: 261 
    

    代码:

    annual_salary = int(input("Salary: "))
    portion_saved = float(input("Percentage to save: ")) 
    total_cost = int(input("Cost of the house: "))
    portion_down_payment = total_cost * 0.25
    current_savings = 0
    rate = 0.04
    number_of_months = 0
    semi_annual_raise = float(input("Raise: "))
    
    while current_savings <= portion_down_payment:
        current_savings += annual_salary * portion_saved / 12
        current_savings += current_savings * rate / 12
        number_of_months += 1
        if number_of_months % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise
        print(number_of_months, current_savings)
    
    print("Enter your annual salary: ", annual_salary)  
    print("Enter the percent of your salary to save, as a decimal: ", portion_saved)
    print("Enter the cost of your dream home: ", total_cost) 
    print("Number of months: ", number_of_months)    
    

1 个答案:

答案 0 :(得分:0)

活期储蓄<预付款项:

应该是这个,这就是为什么你一次过