我显示每年的贷款余额和每年支付的利息减少。第一年和第二年总是搞砸了,导致其余的年份不正确。另外,如何为每个条目打印一个具有指定空间的列,除了像我一样使用空格分隔它们?
我的代码:
int year;
periods = loanDurationYears*12;
double annualBalance = 0;
double annualInterest = 0;
int month = loanDurationYears-(loanDurationYears-1);
balance = loanAmount;
double interestForMonth = balance*((interestRate*.01)/12);
double principalForMonth = monthlyPayment - interestForMonth;
balance = balance - principalForMonth;
System.out.println("Annual balances");
System.out.printf("%s %s %s \n","Year","Interest","Balance");
for(int j=0;j<periods;j++)
{
month++;
year = month/12;
interestForMonth = balance*((interestRate*.01)/12);
principalForMonth = monthlyPayment - interestForMonth;
balance = balance - principalForMonth;
annualBalance = annualBalance + balance;
annualInterest = annualInterest + interestForMonth;
if(month%12 == 0)
{
System.out.printf("%d %.2f %.2f \n",year,annualInterest,annualBalance);
annualBalance = 0;
annualInterest = 0;
}
}
我的输出:
Year Interest Balance
1 4852.43 859718.74
2 5080.12 899718.26
3 4842.34 857208.50
4 4588.01 811738.89
5 4315.96 763103.31
6 4024.98 711081.35
7 3713.73 655437.20
8 3380.81 595918.66
9 3024.71 532255.97
10 2643.82 464160.58
11 2236.40 391323.84
12 1800.62 313415.64
13 1334.49 230082.85
14 835.91 140947.76
15 302.62 45606.39
输出应该如何显示:(除了未对齐的列之外)
Year Interest Loan Balance
1 5965.23 86408.21
2 5715.14 82566.33
3 5447.64 78456.94
4 5161.51 74061.43
5 4855.46 69359.87
6 4528.10 64330.94
7 4177.95 58951.87
8 3803.41 53198.26
9 3402.80 47044.03
10 2974.29 40461.31
11 2515.95 33420.24
12 2025.70 25888.91
13 1501.31 17833.19
14 940.40 9216.58
15 340.45 -0.00
答案 0 :(得分:0)
您获得的启动量不正确,因为您在for循环之前调整了余额。看起来你的for循环期望从完全平衡开始,但它已经减少了。您还应该将month
的增量移动到循环的末尾,或者将其从零开始而不是1。
这一行总是将month
初始化为1.为什么要费心数学呢?
int month = loanDurationYears-(loanDurationYears-1);
答案 1 :(得分:0)
我没有测试过这个或任何东西,但它应该有效。我敢肯定这不是最好的解决方案,但像这样的简单应该可以正常工作。
它只是检查变量的大小,然后根据它的大小使用不同的print语句。此外,随着年份的推出,我已经提出了一些应该修复的代码
if(month%12 == 0)
{
// Set the amount of decimals for all interest rates
DecimalFormat df = new DecimalFormat("#.##");
df.format(annualInterest);
// Get the length of annualInterest
int n = math.floor(annualInterest);
int length = (int)(Math.log10(n)+1);
if (length = 3)
{
// Have 1 less space than normal on the print statement
// Maybe also do a check on the year also as that throws it out when it goes past 10
if (year > 10)
System.out.printf("%d %.2f %.2f \n",year,annualInterest,annualBalance);
else
System.out.printf("%d %.2f %.2f \n",year,annualInterest,annualBalance);
}
if (length = 2)
{
// Have 2 less spaces than normal
}
annualBalance = 0;
annualInterest = 0;
}