python - 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>
解决方案
使用正确的公式得出答案,您可以通过执行以下操作大大简化代码并增加可读性:
# 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}")
推荐阅读
- airflow - 气流 - 没有日志的任务失败
- discord.js - 查看谁邀请了不和谐机器人 (js)
- json - 同一个服务器上同一个dotnet core程序的不同appsettings.json配置
- java - 在 Swing 文本区域中更改(某些文本的)颜色
- python - Docker / Flask - 客户端向 HTTPS 服务器发送 HTTP 请求
- scala - 如何在 Apache Spark 中使用 TypeSafe 配置?
- amazon-web-services - Kubernetes 可以识别/读取 EC2 实例标签吗?
- python - Pandas - 根据记录频率重复行并重命名列
- c++ - 在编译时区分 shared_ptr 和普通类型
- javascript - 在基于 pl2303 的设备的 chrome 中使用 webusb 时发生传输错误