我需要計算一個人每年支付貸款的利息金額,並顯示每年貸款餘額的下降。我瞭解如何在紙上獲取數字,但我無法弄清楚如何爲其編寫代碼,而其他論壇根本沒有幫助。帶java的攤銷計劃
一個例子是什麼它應該看起來像爲:
Enter loan amount: 90000
Enter loan duration in years: 15
Enter interest rate as a percent: 6.75
For a 15 year loan of $90000.00 at 6.75% interest
Monthly payment = $ 796.42
Total interest = $ 53355.33
Yearly Balances
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
我目前有:
import java.util.*;
public class Loan
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int loanAmount, loanDurationYears, month;
double interestRate, monthlyPayment, totalInterest;
System.out.print("Enter loan amount:");
loanAmount = keyboard.nextInt();
System.out.print("Enter loan duration in years:");
loanDurationYears = keyboard.nextInt();
System.out.print("Enter interest rate as a percent:");
interestRate = keyboard.nextDouble();
keyboard.close();
System.out.println("Loan amount: $" + loanAmount);
System.out.println("Loan duration: " + loanDurationYears + " years");
System.out.println("Interest rate: " + interestRate + "%");
monthlyPayment = payment(loanAmount, loanDurationYears, interestRate);
totalInterest = ((monthlyPayment * (loanDurationYears*12))-loanAmount);
printTotals(loanAmount, loanDurationYears, interestRate, monthlyPayment, totalInterest);
}
public static double payment(int loanAmount, int loanDurationYears, double interestRate)
{
int a = loanAmount;
int n = (loanDurationYears*12);
double i = ((interestRate*.01)/12);
double monthlyPayment = a*(Math.pow((1+i),n)*i)/((Math.pow((1+i),n))-1);
return monthlyPayment;
}
public static void printTotals(int loanAmount, int loanDurationYears, double interestRate, double monthlyPayment, double totalInterest)
{
System.out.println("For a " + loanDurationYears + " year loan of $" + loanAmount + " at " + interestRate + "% interest:");
System.out.printf("Monthly payment = $"+ "%.2f", monthlyPayment);
System.out.println();
System.out.printf("Total interest = $"+ "%.2f", totalInterest);
System.out.println();
}
}
當處理貨幣,雙打和浮動不使用雙精度或浮點數時,不會以完美的精度存儲小數點 – gia 2015-04-04 00:06:46
@gia我在另一個論壇上讀到了這個消息,但是我的教授專門告訴我們使用雙打出於某種原因。 – 2015-04-04 00:58:57
他可能希望你失敗,並通過經驗學習 – gia 2015-04-04 01:16:50