房贷计算器含等额本息等额本金的借贷方式c++代码
时间: 2024-10-23 22:20:44 浏览: 72
在C++中编写房贷计算器涉及到一些数学计算,特别是对于等额本息和等额本金这两种常见的还款方式。这里我会给出一个简单的例子,包括如何计算每月还款额以及总利息。请注意,这只是一个基础版本的代码,实际应用可能需要考虑更多细节,如利率调整、提前还款处理等。
```cpp
#include <iostream>
using namespace std;
// 等额本息贷款计算函数
double equalInstallment(double loan_amount, double annual_interest_rate, int years, int months) {
double monthly_interest_rate = annual_interest_rate / 1200;
double payment = (loan_amount * monthly_interest_rate * (1 + monthly_interest_rate)) / (1 - pow(1 + monthly_interest_rate, -months));
return payment;
}
// 等额本金贷款计算函数
double equalPrincipal(double loan_amount, double annual_interest_rate, int years, int months) {
double monthly_interest_rate = annual_interest_rate / 12;
double monthly_payment = loan_amount / years;
double interest = 0;
for (int i = 1; i <= months; ++i) {
double principal = monthly_payment;
interest += loan_amount * ((monthly_interest_rate * (1 + monthly_interest_rate)) / (1 + monthly_interest_rate) ^ i);
monthly_payment -= principal;
}
return interest;
}
int main() {
double loan_amount, annual_interest_rate;
int years, months;
cout << "请输入贷款金额(万元): ";
cin >> loan_amount;
cout << "请输入年利率(百分比): ";
cin >> annual_interest_rate;
cout << "请输入贷款年限(年): ";
cin >> years;
cout << "请输入贷款月数: ";
cin >> months;
double eq_installment = equalInstallment(loan_amount * 10000, annual_interest_rate / 100, years, months); // 将万元转换为元
double eq_principal = equalPrincipal(loan_amount * 10000, annual_interest_rate / 100, years, months);
cout << "等额本息每月还款额: " << eq_installment << " 元" << endl;
cout << "等额本金总利息: " << eq_principal << " 元" << endl;
阅读全文