使用 break 中断
有时,您需要提前结束 while 循环。以债务示例来说,如果您没有足够的 cash 来还清所有 debt,就无法继续偿还。在本练习中,您将添加 if 语句和 break,用来在资金耗尽时提醒您!
while (condition) {
code
if (breaking_condition) {
break
}
}
当满足 breaking_condition 时,while 循环会完全停止,然后执行其后的所有代码行。在这里,该条件就是 cash 用完!
debt 和 cash 已为您定义。
本练习是课程的一部分
R 金融中级
练习说明
- 首先,补全 while 循环,但不要修改被注释的 if 语句。每次循环应将
cash和debt各减去500。运行代码。到debt为0时,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!")
# ___
# }
}