首页 > 解决方案 > CS1301xl Computing in Python 我练习考试抵押问题的公式可能不正确?

问题描述

我想知道这是公式问题还是我的问题。

我在网上查了各种公式。这是 edx 的公式成本 * 月数 * 月率 / 1 - ((1 + 月率) ** 月数)

cost = 150000
rate = 0.0415 
years = 15
rate = rate / 12 
years = years * 12
house_value = cost * years * rate 
house_value2 = (1 + rate) ** years
house_value = house_value / house_value2
house_value = round(house_value, 2)
print("The total cost of the house will be $" + str(house_value))

它应该打印“The total cost of the house will be $201751.36”,但它会打印“The total cost of the house will be $50158.98”</p>

标签: pythonedx

解决方案


使用正确的公式得出答案,您可以通过执行以下操作大大简化代码并增加可读性:

# This is a function that lets you calculate the real mortgage cost over
# and over again given different inputs.
def calculate_mortgage_cost(cost, rate, years):
    # converts the yearly rate to a monthly rate
    monthly_rate = rate / 12
    # converts the years to months
    months = years * 12
    # creates the numerator to the equation
    numerator = cost * months * monthly_rate
    # creates the denominator to the equation
    denominator = 1 - (1 + monthly_rate) ** -months
    #returns the calculated amount
    return numerator / denominator


# sets the calculated amount
house_value = calculate_mortgage_cost(150000, 0.0415, 15)

# This print statement utilizes f strings, which let you format the code
# directly in the print statement and make rounding and conversion
# unnecessary. You have the variable inside the curly braces {}, and then 
# after the colon : the comma , adds the comma to the number and the .2f
# ensures only two places after the decimal get printed.
print(f"The total cost of the house will be ${house_value:,.2f}")

推荐阅读