[英]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.