MIT OCW 6.0001 pset 1b,计算所需的保存月数3个测试,第一个是正确的,另外两个比我的代码给出的多1个月,为什么?

问题描述

#Code
'''

annual_salary = float(input('What is your starting annual salary?'))
monthly_salary = annual_salary/12
portion_saved = float(input('What percentage of your salary will you save each month(in decimals)?'))
Total_cost = float(input('How much is your dream home?'))
semi_annual_raise = float(input('What is your raise every 6 months(in decimals)?'))
portion_down_payment = 0.25*Total_cost
r = 0.04
current_savings = 0
months = 0
while current_savings < portion_down_payment:
    months += 1
    if months % 6 == 0:
        monthly_salary += semi_annual_raise*monthly_salary
    current_savings += portion_saved*monthly_salary + current_savings*r/12
print('Number of months:',months)

#测试 '''

      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

这是3个测试,请帮助 最后2个分别给我的代码结果158和260 它是一种算法,可以根据工资,半年工资,每月储蓄额和投资回报率来计算节省房屋首付所需的月数。

解决方法

#Code

annual_salary = float(input('What is your starting annual salary?'))
monthly_salary = annual_salary/12
portion_saved = float(input('What percentage of your salary will you save each month(in decimals)?'))
Total_cost = float(input('How much is your dream home?'))
semi_annual_raise = float(input('What is your raise every 6 months(in decimals)?'))
portion_down_payment = 0.25*Total_cost
r = 0.04
current_savings = 0
months = 0
while current_savings < portion_down_payment:
    current_savings += portion_saved*monthly_salary + current_savings*r/12
    months += 1
    if months % 6 == 0:
        monthly_salary += semi_annual_raise*monthly_salary
print('Number of months:',months)

#months = 1的错位导致了错误

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...