如何更改循环中的值?

How do I change the value in a loop?

其他变量代码的简单计算。如果 closing 低于 0,我该如何更改它的值?我可以使用什么条件将其值更改为 0?请给我一些例子。即使在其他条件下,closing 的值仍然不会改变。无论我给出什么条件,它都只是在不更改值的情况下运行循环并打印负值本身。是我的代码有问题,还是我在其中使用的条件?

unless closing == 0 then
  term_of_loan.to_i.times do |term_of_loan|
    closing = opening - principal
    closing = closing.round(2)
    if closing < 0 then
      closing = 0
      if sum_interest > total_interest then
        print "\t #{months}| \t #{opening}| \t #{interest}| \t #{sum_interest}| \t #{principal}| \t #{closing} \n"
      else
        print "\t #{months}| \t #{opening}| \t #{interest}| \t #{total_interest}| \t #{principal}| \t #{closing} \n"
      end
    else
      if sum_interest > total_interest then
        print "\t #{months}| \t #{opening}| \t #{interest}| \t #{sum_interest}| \t #{principal}| \t #{closing} \n"
      else
        print "\t #{months}| \t #{opening}| \t #{interest}| \t #{total_interest}| \t #{principal}| \t #{closing} \n"
      end
    end
    opening = closing
  end
end

我相信你想在 closing 变为负数时立即打破循环。

为此,您可以交换条件和循环:

term_of_loan.to_i.times do |term_of_loan|
  unless closing == 0 then
    ...

或显式break负循环:

if closing < 0 then
  closing = 0
  .....
  break # this is it

在你当前的代码中,closing的值被设置为zero,但在它之后,进入下一个循环迭代并且closing = opening - principal(关闭更改为否定。)

希望对您有所帮助。