Scala:使用递归计算利率计算器

时间:2017-10-10 17:17:35

标签: scala recursion

我试图在这个利率计算器上使用递归。现在它打印费率和每月付款等类似的东西,但我希望它打印每个月的付款金额和其他所有内容(而不仅仅是总额),直到用户无需支付更多费用。有没有办法使用递归来做到这一点?

import io.StdIn._

println("Enter the house loan ammount: ")
val loan  = readInt()

println("Enter the number of years you want to take to pay off the loan: ")
val years = readInt()

println("Enter the annual interest rate")
val interestRate =  readInt()

val monthlyPayment = (loan*(interestRate/12))/(1-
(1+interestRate/12)^years*12)

val totalPayment = monthlyPayment*years*12

def monthlyPayment2(monthlyPayment:Int):Unit = {
 if (monthlyPayment>0){
  println(monthlyPayment)
 monthlyPayment2((loan*(interestRate/12))/(1-(1+interestRate/12)^years*12))
}
}
println ("The monthly payment is:"+monthlyPayment)
println("The total payment is:" + totalPayment)

1 个答案:

答案 0 :(得分:0)

每月的月付款是相同的(除了,也许是最后一个),所以,如果您知道金额,那就非常简单:

@tailrec
final def printMonthly(
  principal: Double, 
  amount: Double, 
  month: Int = 1
): Unit = {
  val paid = amount*(month-1)
  val left = principal - paid
  if(left <= amount) {
    println(s"$month: Payment: $left, Total: $principal, Remaining: 0")
  } else {
    println(
     s"$month: Payment: $amount, Total: ${paid + amount}, Remaining: ${left-amount}"
    )
    printMonthly(principal, amount, month+1)
  }
}