首页 > 解决方案 > 最低固定每月付款代码不起作用 - 无限循环?

问题描述

我正在学习 Phyton 的课程,但我发现自己更多地使用 R 方式,我试图解决计算给定金额的最低固定月供的问题。我尝试在 R 中运行以下代码:

balance = 4000
initBalance = balance
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12
month = 0
minPay = 10

calc <- function(month, balance, minPay, monthlyInterestRate) {
  while (month < 12) {
    unpaidBalance = balance - minPay
    balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
    month = month + 1
    print(balance)
  }
}

while(balance > 0) {
  balance = initBalance
  minPay = minPay + 10
  month = 0
  calc(month = month, balance = balance, minPay = minPay, monthlyInterestRate = 0.2/12)
  print(minPay)
}

但是当我运行它时,它会进入一个无限循环。我错过了什么?谢谢你的帮助。

标签: rwhile-loopinfinite-loop

解决方案


尝试这个:

balance = 4000
initBalance = balance
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12
month = 0
minPay = 10

calc <- function(month, balance, minPay, monthlyInterestRate) {
  while (month < 12) {
    unpaidBalance = balance - minPay
    balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
    month = month + 1
    #print(balance)
  }
  return(balance)
}

balance = 4000
initBalance = 4000

while(balance > 0) {
  minPay = minPay + 10
  month = 0
  balance = calc(month = month, balance = initBalance, minPay = minPay, monthlyInterestRate = 0.2/12)
  print(minPay)
}

您可以使用显式公式(请参阅https://en.wikipedia.org/wiki/Equated_monthly_installment):

P = 4000       # principal
r = 0.2 / 12   # rate p.m.
n = 12         # number of payments

A = P*( (r*(1+r)^n)/((1+r)^n-1))  
print(A)
#[1] 370.538

推荐阅读