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

+0

什么是使用的mortage公式? –

+0

抵押贷款的总成本达到$ 365 –

+0

您是否将费率输入为4.5或0.0045? –

回答

2

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

考虑这个重构你的程序:

#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, 7)可能是由于任何类型的舍入误差,即使编译器选择了不同的过载std::pow(因为C++ 11,积分参数被提升为double)。