if-else if-else语句和括号 [英] if - else if - else statement and brackets

查看:193
本文介绍了if-else if-else语句和括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解编写"if-else if"语句的通常方法如下:

I understand the usual way to write an "if - else if" statement is as follow:

if (2==1) {
  print("1")
} else if (2==2) {
  print("2")
} else {
  print("3")
}

if (2==1) {print("1") 
} else if (2==2) {print("2")
} else print("3")

相反,如果我这样写

if (2==1) {
  print("1")
} 
else if (2==2) {
  print("2")
}
else (print("3"))

或这种方式:

if (2==1) print("1") 
else if (2==2) print("2")
else print("3")

该语句不起作用.您能解释一下为什么}必须在同一行中的elseelse if之前吗?是否还有其他方法可以在R中编写if-else if-else语句,尤其是没有括号的情况下?

the statement does NOT work. Can you explain me why } must precede else or else if in the same line? Are there any other way of writing the if-else if-else statement in R, especially without brackets?

推荐答案

R逐行读取这些命令,因此它认为在if语句后执行表达式之后您就完成了.请记住,您可以使用if 而无需添加else.

R reads these commands line by line, so it thinks you're done after executing the expression after the if statement. Remember, you can use if without adding else.

您的第三个示例将在函数中工作,因为整个函数是在执行之前定义的,所以R 知道尚未完成(在if() do之后).

Your third example will work in a function, because the whole function is defined before being executed, so R knows it wasn't done yet (after if() do).

这篇关于if-else if-else语句和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆