加上中斷
有時候你需要提早結束 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發生了什麼事? - 出現負的 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!")
# ___
# }
}