繁体   English   中英

这个抵押公式我做错了什么?

[英]What am I doing wrong with this mortgage formula?

#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));)。 我不确定我的代码有什么问题。

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

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

#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';
}

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

Enter the amount of your mortage loan (dollars):
200000
Enter the interest rate (percentage):
4.5
Enter the term of your loan (years):
30

Your monthly payment is: $ 1013.37

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM