【问题标题】:Minimum fixed monthly payment code is not working - infinite loop?最低固定每月付款代码不起作用 - 无限循环?
【发布时间】:2019-05-05 04:02:47
【问题描述】:

我正在学习 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)
}

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

【问题讨论】:

  • 您没有在第二个循环中更新balance。它永远不会变成&lt;= 0

标签: r while-loop infinite-loop


【解决方案1】:

试试这个:

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

【讨论】:

  • 嗨@emsinko。我不确定如何在 while 循环中改变平衡,但现在我明白了。谢谢。
猜你喜欢
  • 2018-05-02
  • 1970-01-01
  • 2021-02-07
  • 2016-05-06
  • 2016-01-25
  • 2015-04-13
  • 2014-07-13
  • 2011-01-28
  • 2013-05-30
相关资源
最近更新 更多