会在 If 里面再写 If 吗?
有时需要使用嵌套的 if 语句来实现更细的控制。在下面的练习中,您将在尝试卖出之前,添加一个 if 语句来检查您是否持有微软股票的份额。
下面是嵌套 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 {
___
}
}