为什么我会从这个简单的python函数获得意外结果?

时间:2020-07-08 16:24:21

标签: python-3.x

我正在通过MIT OpenCourseWare工作,我遇到了一个本应非常简单的功能问题。下面的代码似乎有效,但是我得到的答案对于非常接近都是正确的。例如,如果您输入:

annual_salary = 120000
portion_saved = .10
total_cost = 1000000

它输出182,但预期结果是183。但是,如果我输入:

annual_salary = 80000
portion_saved = .15
total_cost = 500000

我得到105,这是预期结果。如果删除if分支并使用相同的输入,则会得到183(正确)和106(错误)。我完全感到困惑。

def calc_savings(annual_salary, portion_saved, total_cost):
    portion_down_payment = .25
    r = 0.04 # return on investment
    monthly_salary = annual_salary / 12
    num_months = 1
    current_savings = 0

    while current_savings < total_cost * portion_down_payment:
        pre_interest = current_savings + (monthly_salary * portion_saved)
        current_savings = pre_interest + (pre_interest * r / 12)
        if current_savings >= total_cost * portion_down_payment:
            return num_months
        num_months += 1
    return num_months
    
annual_salary = int(input("Enter your annual_salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the cost of your dream home: "))

print("Number of months: ", calc_savings(annual_salary, portion_saved, total_cost))

1 个答案:

答案 0 :(得分:1)

如果您添加投资回报(current_savings * r / 12),然后然后添加月投资(monthly_salary * portion_saved),它将返回正确的答案。您只需要切换添加它们的顺序即可。

相关问题