c++制作一个含等额本息与等额本金的房贷计算器
时间: 2024-11-08 19:22:52 浏览: 16
在C++中制作房贷计算器,可以包含两个部分:等额本息还款法和等额本金还款法。这里是一个简单的示例程序框架,我们将使用结构体和函数来实现这两种计算方式:
```cpp
#include <iostream>
#include <cmath>
// 定义贷款信息结构体
struct LoanInfo {
double amount; // 贷款金额
double interest_rate; // 年利率
int term_years; // 还款年数
int payment_interval; // 每月还款间隔
bool method; // 选择还款方式,0 - 等额本息,1 - 等额本金
};
// 计算等额本息还款
double equalInstallmentPayment(LoanInfo loan) {
double monthly_interest = loan.interest_rate / 1200;
double numerator = loan.amount * (monthly_interest * pow(1 + monthly_interest, loan.term_years * 12));
double denominator = pow(1 + monthly_interest, loan.term_years * 12) - 1;
return numerator / denominator;
}
// 计算等额本金还款
double equalPrincipalPayment(LoanInfo loan) {
double total_payment = loan.amount * loan.interest_rate * (loan.term_years * 12);
double remaining_amount = loan.amount;
double monthly_payment = total_payment / loan.term_years;
for (int month = 1; month <= loan.term_years * 12; ++month) {
if (remaining_amount > 0) {
double interest = remaining_amount * loan.interest_rate / 12;
monthly_payment -= interest;
remaining_amount -= monthly_payment;
}
}
return monthly_payment;
}
// 主函数
int main() {
LoanInfo loan;
std::cout << "请输入贷款金额(元):";
std::cin >> loan.amount;
std::cout << "请输入年利率(百分比):";
std::cin >> loan.interest_rate;
std::cout << "请输入贷款年限(年):";
std::cin >> loan.term_years;
std::cout << "请选择还款方式(0 - 等额本息,1 - 等额本金):";
std::cin >> loan.method;
double payment;
if (loan.method == 0)
payment = equalInstallmentPayment(loan);
else if (loan.method == 1)
payment = equalPrincipalPayment(loan);
else
return 1; // 错误输入
std::cout << "每月还款额为:" << payment << " 元。\n";
return 0;
}
```
阅读全文