开始使用免费开始使用

使用 break 中断

有时,您需要提前结束 while 循环。以债务示例来说,如果您没有足够的 cash 来还清所有 debt,就无法继续偿还。在本练习中,您将添加 if 语句和 break,用来在资金耗尽时提醒您!

while (condition) {
    code
    if (breaking_condition) {
        break
    }
}

当满足 breaking_condition 时,while 循环会完全停止,然后执行其后的所有代码行。在这里,该条件就是 cash 用完!

debtcash 已为您定义。

本练习是课程的一部分

R 金融中级

查看课程

练习说明

  • 首先,补全 while 循环,但不要修改被注释的 if 语句。每次循环应将 cashdebt 各减去 500。运行代码。到 debt0 时,cash 发生了什么?
  • 现金为负数?这可不妙!去掉注释并补全 if 语句。当 cash 用完时应 break,也就是当 cash 等于 0 时。再次运行整个程序。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# debt and cash
debt <- 5000
cash <- 4000

# Pay off your debt...if you can!
while (debt ___ 0) {
  debt <- debt - ___
  cash <- cash - ___
  print(paste("Debt remaining:", debt, "and Cash remaining:", cash))

  # if (___ == ___) {
  #   print("You ran out of cash!")
  #   ___
  # }
}
编辑并运行代码