c++不使用函数制作一个含等额本息与等额本金的房贷计算器
时间: 2024-11-08 08:20:48 浏览: 51
在C++中,我们可以不直接使用函数创建一个房贷计算器,而是通过类和结构体结合控制台输入来模拟计算过程。这里我们简单地构建一个结构体来存储贷款的相关信息,如贷款总额、利率、期限等,并提供一些成员函数来实现等额本息(按月还款)和等额本金(每月偿还本金固定,利息逐期减少)的计算。
首先,创建一个简单的结构体:
```cpp
#include <iostream>
#include <cmath>
// 贷款信息结构体
struct Loan {
double loanAmount;
double annualInterestRate;
int loanTermInYears;
// 等额本息和等额本金计算方法可以添加到这里
};
// 计算等额本息的月供
double calculateMonthlyAmortizationEMI(Loan& loan) {
double monthlyInterestRate = loan.annualInterestRate / 1200; // 将年利率转换为月利率
double totalPayments = loan.loanTermInYears * 12; // 总月数
return (loan.loanAmount * monthlyInterestRate) / (1 - pow(1 + monthlyInterestRate, -totalPayments));
}
// 计算等额本金的月供
double calculateMonthlyAmortizationPP(Loan& loan) {
double monthlyInterestRate = loan.annualInterestRate / 1200;
double remainingBalance = loan.loanAmount;
double monthlyPayment = loan.loanAmount / loanTermInYears;
for (int i = 0; i < totalPayments; ++i) {
double interestOnly = remainingBalance * monthlyInterestRate;
monthlyPayment -= interestOnly;
remainingBalance -= monthlyPayment;
}
return monthlyPayment;
}
```
然后,创建主函数来获取用户输入并展示结果:
```cpp
int main() {
Loan loan;
std::cout << "请输入贷款金额: ";
std::cin >> loan.loanAmount;
std::cout << "请输入年利率: ";
std::cin >> loan.annualInterestRate;
std::cout << "请输入贷款年限(年): ";
std::cin >> loan.loanTermInYears;
double emi = calculateMonthlyAmortizationEMI(loan);
double pp = calculateMonthlyAmortizationPP(loan);
std::cout << "等额本息月供: " << emi << "\n";
std::cout << "等额本金月供: " << pp << "\n";
return 0;
}
```
这个程序会提示用户输入贷款金额、利率和贷款年限,然后分别显示等额本息和等额本金的月供。注意这只是一个基础示例,实际应用可能需要更完善的错误处理和用户交互界面。
阅读全文