【问题标题】:While loop removes iteration when variable is repeated当变量重复时,while循环删除迭代
【发布时间】:2020-04-27 02:19:14
【问题描述】:

我正在学习麻省理工学院的 Python 入门课程,以便在隔离期间有效地打发我的时间,但我发现了一些让我有点困惑的东西。

我只会发布代码的 sn-p,因为我只关注这个 while 循环。如果我运行下面的循环,我会得到 159 个月的正确答案:

while current_savings < down_payment:
    current_savings += monthly_savings + (current_savings*0.04)/12
    months += 1

但如果我运行下一个,它会给我一个 158 个月的答案:

while current_savings < down_payment:
    current_savings += monthly_savings
    current_savings += (current_savings*0.04)/12
    months += 1

我只是有点困惑,为什么第二行代码会休假一个月。谁能解释一下这段代码是如何被阅读的?

【问题讨论】:

  • 问题是在第二个中,当前储蓄在乘以 0.04 之前由每月储蓄更新。所以基本上你有current_savings += ((current_savings+monthly_savings)*0.04)/12
  • 操作顺序。在第一个循环中,(current_savings*.04)/12 在添加 monthly_savings 之前执行。

标签: python while-loop syntax


【解决方案1】:

第一个

在这个current_savings(current_savings*0.04)/12 的第一个值为current_savings

while current_savings < down_payment:
    current_savings = current_savings + monthly_savings + (current_savings*0.04)/12
    months += 1

第二个:

while current_savings < down_payment:
    current_savings = current_savings + monthly_savings
    current_savings = current_savings + (current_savings*0.04)/12 //here current_savings in (current_savings*0.04)/12 has changed after the line above
    months += 1

我去掉了+=,以便在逻辑上更容易理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2013-05-20
    • 2013-01-29
    • 2019-11-13
    • 2011-11-16
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多