此语句也称为嵌套if-else语句。 if语句后面是可选的else if ..... else语句。该语句用于在单个if ...... else if语句中测试各种条件。当我们使用if .... else if ..... else语句时,需要牢记一些关键点。这些要点如下:
If-else语句的基本语法如下:
if(boolean_expression 1) { //This block executes when the boolean expression 1 is true. } else if( boolean_expression 2) { //This block executes when the boolean expression 2 is true. } else if( boolean_expression 3) { //This block executes when the boolean expression 3 is true. } else { //This block executes when none of the above condition is true. }
流程图
age <- readline(prompt="Enter age: ") age <- as.integer(age) if(age<18) print("You are child") else if(age>30) print("You are old guy") else print("You are adult")
输出:
marks=83; if(marks>75){ print("First class") }else if(marks>65){ print("Second class") }else if(marks>55){ print("Third class") }else{ print("Fail") }
输出:
cat("1) For Addition\n") cat("2) For Subtraction\n") cat("3) For Division\n") cat("4) For multiplication\n") n1<-readline(prompt="Enter first number:") n2<-readline(prompt="Enter second number:") choice<-readline(prompt="Enter your choice:") n1<- as.integer(n1) n2<- as.integer(n2) choice<- as.integer(choice) if(choice==1){ sum <-(n1+n2) cat("sum=",sum) }else if(choice==2){ sub<-(n1-n2) cat("sub=",sub) }else if(choice==3){ div<-n1/n2 cat("Division=",div) }else if(choice==4){ mul<-n1*n2 cat("mul=",mul) }else{ cat("wrong choice") }
输出:
x <- c("Learnfk","is","the","key","of","success")
if("Success" %in% x) {
print("success is found in the first time")
} else if ("success" %in% x) {
print("success is found in the second time")
} else {
print("No success found")
}
输出:
n1=4 n2=87 n3=43 n4=74 if(n1>n2){ if(n1>n3&&n1>n4){ largest=n1 } }else if(n2>n3){ if(n2>n1&&n2>n4){ largest=n2 } }else if(n3>n4){ if(n3>n1&&n3>n2){ largest=n3 } }else{ largest=n4 } cat("THE LEARNFK.COM Largest number is =",largest)
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)