【问题标题】:What am I doing wrong with this mortgage formula?我对这个抵押贷款公式做错了什么?
【发布时间】:2017-10-12 05:26:12
【问题描述】:
#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 美元。我的教授也给了我们该代码(monthlyPayment = amount * rate / (1.0 – pow(rate + 1, -term));)。我不确定我的代码有什么问题。

【问题讨论】:

  • 按揭公式是什么?
  • 抵押贷款总成本为 365 美元
  • 您输入的汇率是 4.5 还是 0.0045?
  • 你认为你没有从你的函数返回的所有局部变量发生了什么?
  • @HariomSingh 使用的抵押贷款公式是monthlyPayment = 本金 * 利率 / ( 1.0 – pow(rate + 1, -term));

标签: c++


【解决方案1】:

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

考虑对您的程序进行这种重构:

#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,67) 的细微差别可能是由于任何类型的舍入错误,甚至是编译器选择的 std::pow 的不同重载(自 C++ 起11、积分参数提升为double)。

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2015-06-30
    • 2013-06-10
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多