我用这个抵押贷款公式做错了什么

What am I doing wrong with this mortgage formula?

本文关键字:错了 什么 抵押贷款      更新时间:2023-10-16
#include <iostream>
#include <cmath>
using namespace std;

/* FINDS AND INITIALIZES TERM */
void findTerm(int t) {
int term = t * 12;
}
/* FINDS AND INITIALIZES RATE */
void findRate(double r) {
double rate = r / 1200.0;
}
/* INITALIZES AMOUNT OF LOAN*/
void findAmount(int amount) {
int num1 = 0.0;
}
void findPayment(int amount, double rate, int term) {
int monthlyPayment = amount * rate / ( 1.0 -pow(rate + 1, -term));
cout<<"Your monthly payment is $"<<monthlyPayment<<". ";
}

这是主要功能。

int main() {
int t, a, payment;
double r;
cout<<"Enter the amount of your mortage loan: n ";
cin>>a;
cout<<"Enter the interest rate: n";
cin>>r;
cout<<"Enter the term of your loan: n";
cin>>t;
findPayment(a, r, t); // calls findPayment to calculate monthly payment.
return 0;
}

一遍又一遍地运行它,但它仍然给了我不正确的数量。我的教授给我们举了一个例子,是这样的:贷款=$200,000

利率=4.5%

期限:30年

findFormula() 函数应该产生 1013.67 美元的抵押贷款付款。我的教授也给了我们这个代码(每月付款 = 金额 * 费率/( 1.0 – pow(费率 + 1, -term));)。我不确定我的代码出了什么问题。

公式可能没问题,但您没有返回或使用转换函数中的任何值,因此其输入是错误的。

请考虑对程序进行以下重构:

#include <iostream>
#include <iomanip>      // for std::setprecision and std::fixed
#include <cmath>
namespace mortgage {
int months_from_years(int years) {
    return years * 12;
}
double monthly_rate_from(double yearly_rate) {
    return yearly_rate / 1200.0;
}
double monthly_payment(int amount, double yearly_rate, int years)
{
    double rate = monthly_rate_from(yearly_rate);
    int term = months_from_years(years);
    return amount * rate / ( 1.0 - std::pow(rate + 1.0, -term));
}
} // end of namespace 'mortgage'
int main()
{
    using std::cout;
    using std::cin;
    int amount;
    cout << "Enter the amount of your mortage loan (dollars):n";
    cin >> amount;
    double rate;
    cout << "Enter the interest rate (percentage):n";
    cin >> rate;
    int term_in_years;
    cout << "Enter the term of your loan (years):n";
    cin >> term_in_years;
    cout << "nYour monthly payment is: $ " << std::setprecision(2) << std::fixed
        << mortgage::monthly_payment(amount, rate, term_in_years) << 'n';
}

仍然缺乏对用户输入的任何检查,但给定示例的值,它输出:

输入您的抵押贷款金额(美元):200000输入利率(百分比):4.5输入您的贷款期限(年):30您的每月付款是: $ 1013.37

与预期输出 (1013,6 7) 的细微差异可能是由于任何类型的舍入误差,甚至是编译器选择的不同重载std::pow(自 C++11 以来,积分参数被提升为 double )。