计算代码
class Solution {
public:
int getSum(int a, int b) {
double base = 2200000;//2160269.31;
double ratio = 0.04165;
int totalMonths = 360;
double monthlyPayout = base * (ratio/12) * pow((1 + ratio/12), totalMonths) / (pow((1 + ratio/12), totalMonths) - 1);
double totalPayout = monthlyPayout * totalMonths;
//cout << monthlyPayout <<endl;
int monthIndex = 1;
// 在第indexByAdvance个月决定还款
int indexByAdvance = 24;
bool flag = false;
// 提前还款的额度
double x = 200000;
// 假设当前投资别的东西年收益率
double ratioByInvest = 0.045;
// 不提前还款,到第monthIndex个月为止的总利息
double sumInterest = 0;
// 不提前还款,到第monthIndex个月为止的剩余本金
double leftBase = base;
// 不提前还款剩余的总利息总和
double leftInterest = monthlyPayout*totalMonths - base;
// 提前还款剩余的总利息总和
// 提前还款(设在第K个月提前还款x元,K<monthIndex),到第monthIndex个月为止的总利息
double sumInterestByAdvance = 0;
// 提前还款(设在第K个月提前还款x元,K<monthIndex),到第monthIndex个月为止的剩余本金
double leftBaseByAdvance = base;
// x元做投资的总回报
double paybackByInvest = 0;
while(monthIndex <= totalMonths && leftBaseByAdvance >=0) {
/*
计算到第monthIndex个月为止的总支出(查看剩余本金和已经支出的利息):
1. 假设不提前还款
(1)到第monthIndex个月为止的总利息 = monthlyPayout * monthIndex;
2. 在第K个月提前还款X元的总支出 = base - monthlyPayout * (monthIndex - k) - ()
*/
if (monthIndex == indexByAdvance) {
leftBaseByAdvance = leftBaseByAdvance - x;
}
if (monthIndex >= indexByAdvance) {
double cInterest = leftBaseByAdvance * (ratio/12);
double cBase = monthlyPayout - cInterest;
leftBaseByAdvance = leftBaseByAdvance - cBase;
sumInterestByAdvance = sumInterestByAdvance + cInterest;
flag = true;
// 假设拿x元做投资的回报金额是:
paybackByInvest = paybackByInvest + (x+paybackByInvest)*(ratioByInvest/12);
//cout<<"monthIndex: "<<monthIndex<<", paybackByInvest: "<<paybackByInvest<<endl;
}
double curInterest = leftBase * (ratio/12);
double curBase = monthlyPayout - curInterest;
leftBase = leftBase - curBase;
sumInterest = sumInterest + curInterest;
if (!flag) {
sumInterestByAdvance = sumInterest;
leftBaseByAdvance = leftBase;
}
// 作对比
/*
if ((totalPayout -base - sumInterest - paybackByInvest) > (monthlyPayout*333+x - base - sumInterestByAdvance) && (monthIndex >= indexByAdvance) ) {
cout<<"提前还款在第"<<monthIndex<<"个月开始奏效"<<endl;
}*/
if ((sumInterest-paybackByInvest) > sumInterestByAdvance) {
cout<<"提前还款在第"<<monthIndex<<"个月开始奏效"<<endl;
}
//cout<<monthlyPayout<<endl;
//cout<<sumInterest<<endl;
//cout<<monthIndex<<":"<<leftBaseByAdvance<<":"<<sumInterestByAdvance<<endl;
//cout<<monthIndex<<":"<<leftBase<<":"<<sumInterest<<endl;
cout<<"monthIndex: "<<monthIndex<<", sumInterest: "<<sumInterest - paybackByInvest<<", sumInterestByAdvance: "<<sumInterestByAdvance<<endl;
//cout<<"monthIndex: "<<monthIndex<<", paybackByInvest: "<<paybackByInvest<<", leftInterest: "<<totalPayout -base - sumInterest - paybackByInvest<<",leftBase: "<<leftBase<<", leftInterestInAdvance:"<<monthlyPayout*333+x - base - sumInterestByAdvance<<", leftBaseInAdvance: "<<leftBaseByAdvance<<endl;
monthIndex++;
//cout<<monthIndex<<endl;
}
return 1;
}
};
结论
似乎只要是投资利率高于还款利率就不亏。
网友评论