我在C ++中还很陌生,遇到了一些麻烦。为此,我正在尝试创建抵押计算器。我遇到的问题是它没有打印出正确的月付款和总还款额。这是我到目前为止所拥有的:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main () {
double annualInterestRate(0); // yearly interest rate
double loanAmount(0); // the amount of the loan
double monthlyInterestRate(0); // interest rate amount monthly
double numberofPayments(0); // the amount of payments
double totalYearsToRepay(0); // years needed to payback
double totalPayBack(0); // total amount being paid back
double monthlyPayment(0);
while (true) {
cout << "Enter the amount of the loan:";
cin >> loanAmount;
cout << "Enter annual interest rate in decimal term (example 0.075):";
cin >> annualInterestRate;
cout << "Enter the length of the loan in years:";
cin >> totalYearsToRepay;
loanAmount = loanAmount;
cout << "loanAmount: $" << setprecision(2) << fixed << loanAmount << endl;
annualInterestRate = annualInterestRate;
cout << "annualInterestRate: $" << setprecision(5) << fixed << annualInterestRate << endl;
cout << "totalYearsToRepay: " << setprecision(0) << fixed << totalYearsToRepay << endl;
// find monthly interest rate.
monthlyInterestRate=annualInterestRate / 12;
totalYearsToRepay = totalYearsToRepay;
numberofPayments = totalYearsToRepay* 12;
monthlyPayment = (loanAmount * (monthlyInterestRate) * totalYearsToRepay) / (totalYearsToRepay-1);
cout << "Monthly Payment: $" << setprecision(2) << fixed << monthlyPayment << endl;
totalPayBack = (monthlyPayment) * (numberofPayments);
cout << "Total Pay Back: $" << setprecision (2) << fixed << totalPayBack << endl;
}
}
这是应打印内容的示例:
Loan Amount: $50000.00
Annual Interest Rate: 0.06250
Years to repay: 10
Monthly Payment: $561.40
Total Pay Back: $67368.06
我没有得到每月的还款额和总还款额。我不知道数学部分出了什么问题。请帮忙!给定的公式为monthly payment= loanAmount * monthlyInterestRate * powerFactor / powerFactor -1
,其中powerFactor = (1+monthlyInterestRate)^numberofpayments
答案 0 :(得分:0)
我将使用此处https://www.thecalculatorsite.com/articles/finance/compound-interest-formula.php
所述的公式然后我将A值除以该人必须还清该公式中称为A的总价的月份数。
您正在寻找所谓的“复合利率”。
答案 1 :(得分:0)
在发布的代码中有此行
monthlyPayment = (loanAmount * (monthlyInterestRate) * totalYearsToRepay)
/ (totalYearsToRepay-1);
在评论中,OP清除
给出的公式是:
每月付款=贷款金额*每月利率* powerFactor / powerFactor-1
在哪里
powerFactor =(1+每月利率)^付款次数
可以将其转换为这些C ++代码行:
double powerFactor = std::pow(1.0 + monthlyInterestRate, numberofPayments);
double monthlyPayment = loanAmount * monthlyInterestRate * powerFactor
/ (powerFactor - 1.0);
// The parenthesis, here, are needed, due to standard math operator precedence
值得注意的是,代码还包含其他问题,例如分配给自己的变量或永无止境的循环
while (true)
{
// Put a break statement somewhere or change the condition
}