使用python写一个房贷计算器,需要写注释
时间: 2024-06-12 14:04:53 浏览: 116
python实现房贷计算器
# 导入math库,用于计算幂函数
import math
# 定义房贷计算器类
class MortgageCalculator:
# 初始化函数,传入贷款总额、贷款年限和年利率三个参数
def __init__(self, loan_amount, loan_term, interest_rate):
self.loan_amount = loan_amount
self.loan_term = loan_term
self.interest_rate = interest_rate
# 计算每月还款额
def monthly_payment(self):
# 将年利率转换为月利率
monthly_rate = self.interest_rate / 12
# 计算每月还款额
monthly_payment = self.loan_amount * monthly_rate * math.pow(1 + monthly_rate, self.loan_term * 12) / (math.pow(1 + monthly_rate, self.loan_term * 12) - 1)
return monthly_payment
# 计算还款总额
def total_payment(self):
total_payment = self.monthly_payment() * self.loan_term * 12
return total_payment
# 计算支付利息总额
def total_interest(self):
total_interest = self.total_payment() - self.loan_amount
return total_interest
# 输出计算结果
def print_result(self):
print('贷款总额:%.2f元' % self.loan_amount)
print('贷款年限:%d年' % self.loan_term)
print('年利率:%.2f%%' % (self.interest_rate * 100))
print('每月还款额:%.2f元' % self.monthly_payment())
print('还款总额:%.2f元' % self.total_payment())
print('支付利息总额:%.2f元' % self.total_interest())
# 示例代码,计算贷款总额为100万元,贷款年限为20年,年利率为5%的房贷计算器
mortgage_calculator = MortgageCalculator(1000000, 20, 0.05)
mortgage_calculator.print_result()
阅读全文