If 裡面可以再放 If 嗎?
有時候使用巢狀 if 敘述可以提供更細緻的控制。在這個練習中,你會在嘗試賣出之前,先加入一個 if,檢查你是否持有 Microsoft 的股票。
以下是巢狀 if 敘述的結構,你應該會覺得很眼熟:
if(condition1) {
if(condition2) {
code if both pass
} else {
code if 1 passes, 2 fails
}
} else {
code if 1 fails
}
變數 micr 和 shares 已為你建立。
本練習屬於課程
R 金融中級
練習說明
- 在巢狀 if 中先檢查
shares是否大於或等於1,再決定是否賣出。 - 若為真,則印出
"Sell!"。 - 否則,印出
"Not enough shares to sell!"。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
micr <- 105.67
shares <- 1
# Fill in the blanks
if( micr < 55 ) {
print("Buy!")
} else if( micr >= 55 & micr < 75 ) {
print("Do nothing!")
} else {
if( ___ ) {
___
} else {
___
}
}