房贷计算器c++代码
时间: 2024-10-23 10:01:21 浏览: 35
自由还款 房贷计算器 c++版
在C++编写房贷计算器代码时,首先我们需要考虑一些基本的变量,如贷款金额、年利率、贷款期限、还款方式等。这里是一个简单的例子,使用控制台输入并计算每月还款额:
```cpp
#include <iostream>
#include <cmath>
// 定义房贷计算函数
double calculateMonthlyPayment(double loanAmount, double annualInterestRate, int years, int monthsPerYear, bool isFixedRate) {
double monthlyInterestRate = annualInterestRate / 100.0 / monthsPerYear;
if (isFixedRate) {
return loanAmount * monthlyInterestRate * (1 + monthlyInterestRate) * years * 12 / ((1 + monthlyInterestRate) * years * 12 - 1);
} else { // 如果是浮动利率,这里仅作为示例,实际需获取当前月利率
// 假设固定按揭比例
double mortgageRatio = 0.8; // 比如80%
return loanAmount * mortgageRatio / (years * monthsPerYear * (1 + annualInterestRate / 12));
}
}
int main() {
double loanAmount, annualInterestRate;
int years, monthsPerYear;
std::cout << "请输入贷款金额(元): ";
std::cin >> loanAmount;
std::cout << "请输入年利率(%): ";
std::cin >> annualInterestRate;
std::cout << "请输入贷款年限(年): ";
std::cin >> years;
std::cout << "请输入每年的还款月数: ";
std::cin >> monthsPerYear;
bool isFixedRate;
std::cout << "贷款是固定利率还是浮动利率? (1-固定,2-浮动): ";
std::cin >> isFixedRate;
if (isFixedRate == 1) {
double monthlyPayment = calculateMonthlyPayment(loanAmount, annualInterestRate, years, monthsPerYear, true);
std::cout << "每月应还款额为: " << monthlyPayment << "元\n";
} else if (isFixedRate == 2) {
double monthlyPayment = calculateMonthlyPayment(loanAmount, annualInterestRate, years, monthsPerYear, false);
std::cout << "每月应还款额为: " << monthlyPayment << "元\n";
} else {
std::cout << "无效的选择。\n";
}
return 0;
}
```
阅读全文