2017-10-12 62 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)。