停止 while 迴圈:break
在極少數情況下,超速其實是必要的:例如颶風正在接近,而你必須盡快撤離。這種情況下,你不會希望駕駛助理一直跳出超速提醒,對吧?
這正好是把 break 敘述加入你正在編寫的 while 迴圈的好時機。記得 break 是控制敘述。當 R 執行到它時,while 迴圈會被直接終止。
本練習屬於課程
R 中級
練習說明
調整 while 迴圈,當車輛的 speed 大於 80 時就終止迴圈。這次 speed 變數已經初始化為 88;請保持不變。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize the speed variable
speed <- 88
while (speed > 30) {
print(paste("Your speed is", speed))
# Break the while loop when speed exceeds 80
if (___) {
___
}
if (speed > 48) {
print("Slow down big time!")
speed <- speed - 11
} else {
print("Slow down!")
speed <- speed - 6
}
}