项目2-3 计算贷款的定期还款额
在这个项目中,我们将要创建一个程序用来计算贷款的定期还款额度,比如买车的贷款。指定本金,贷款的时间长度,每年偿还的次数,以及贷款利率,程序就会计算出每次应该偿还的额度。因为这里涉及到小数的运算,我们需要使用浮点类型的数据来进行计算。既然double类型是最常用的浮点类型,在这个项目中我们就是用double类型的浮点数。这个程序将使用到另外的一个C++库函数:pow()。计算定期还款金额的公式如下:
这里IntRate代表利率,Principal代表本金,PayPerYear代表每年偿还贷款的次数,NumYears 代表贷款的年限。
注意在上面的公式中使用到了幂运算,在程序中我们将使用pow()函数来完成这个功能。下面的代码显示了我们应该怎么使用这个函数:
result = pow ( base, exp);
pow()函数返回base的exp次幂。传入到pow()中的参数是double类型的,返回值也是double类型的。
步骤:
1. 创建一个新的文件命名为RegPay.cpp。
2. 下面是程序中将使用到的变量:
double Principal; //原始的本金
double IntRate; //利率,例如,0.075
double PayPerYear; //每年偿还的次数
double NumYears; //偿还的年限
double Payment; //每次偿还的数额
double number, denom; // 临时的变量
double b,e; //底数,指数
注意上面在变量声明后的注释,用于描述变量的作用,这样有助于别人阅读我们的程序,也能很容易地明白各个变量的作用。虽然本书的大部分小程序都没有包含这样的细节,但是这种做法确实很好,特别是当程序变得越来越大,越来越复杂的时候。
3. 添加下面的代码,其中包括输入贷款的信息:
count << "Enter principal:";
cin >> Principal;
count << "Enter interest rate(i.e.,0.075): ";
cin >> IntRate;
count << "Enter number of years: ";
cin >> NumYears;
4. 添加下面的代码来进行运算:
number = IntRate * Principal / PayPerYEar;
e = -(PayPerYear * NumYears );
b = (IntRage / PayPerYears )+1
denom = 1 - pow(b,e);
Payment = number / denom;
5. 最后,输出还款额:
cout << "Payment is " << Payment;
6. 完整的RegPay.cpp程序如下:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double Principal; // original principal
double IntRate; // interest rate, such as 0.075
double PayPerYear; // number of payments per year
double NumYears; // number of years
double Payment; // the regular payment
double numer, denom; // temporary work variables
double b, e; // base and exponent for call to pow()
cout << "Enter principal: ";
cin >> Principal;
cout << "Enter interest rate (i.e., 0.075): ";
cin >> IntRate;
cout << "Enter number of payments per year: ";
cin >> PayPerYear;
cout << "Enter number of years: ";
cin >> NumYears; numer = IntRate * Principal / PayPerYear;
e = -(PayPerYear * NumYears);
b = (IntRate / PayPerYear) + 1;
denom = 1 - pow(b, e);
Payment = numer / denom;
cout << "Payment is " << Payment;
return 0;
}
程序可能的输出结果如下:
Enter principal: 10000
Enter interest rate (i.e., 0.075): 0.075
Enter number of payments per year: 12
Enter number of years: 5
Payment is 200.379
我们可以自己修改程序,输出共计需要支付的利息。