我用这个抵押贷款公式做错了什么
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 美元的抵押贷款付款。我的教授也给了我们这个代码(每月付款 = 金额 * 费率/( 1.0 – pow(费率 + 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';
}
它仍然缺乏对用户输入的任何检查,但给定示例的值,它输出:
输入您的抵押贷款金额(美元):200000输入利率(百分比):4.5输入您的贷款期限(年):30您的每月付款是: $ 1013.37
与预期输出 (1013,6 7) 的细微差异可能是由于任何类型的舍入误差,甚至是编译器选择的不同重载std::pow
(自 C++11 以来,积分参数被提升为 double
)。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 没有输出的合并排序我做错了什么?
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 在C++中使用 AKS 素数测试计算双胞胎素数 我做错了什么?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- FFMPEG,C++,内存泄漏,我做错了什么?
- 我做错了什么?反向字符串 C++
- 我在这个课上做错了什么?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 在不使用内置库函数的情况下添加字符串,我做错了什么?
- 我做错了什么?GetDiskFreeSpaceExA的功能根本不起作用
- 我在查找和字符串上做错了什么?
- 我正在尝试用 c++ 制作一个日志记录框架,但信息没有传递给记录器的子组件,我做错了什么?
- 我在尝试将多个值push_back向量时出错。我做错了什么?
- 插入排序:我做错了什么?