gpt4 book ai didi

c++ - 这个抵押贷款公式我做错了什么?

转载 作者:搜寻专家 更新时间:2023-10-31 02:09:14 25 4
gpt4 key购买 nike

#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):200000Enter the interest rate (percentage):4.5Enter the term of your loan (years):30Your monthly payment is: $ 1013.37

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

关于c++ - 这个抵押贷款公式我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com