该语句也称为嵌套if-else语句。 if语句后面是可选的else if ….. else语句。该语句用于在单个if …… else if语句中测试各种条件。当我们使用if …. else if ….. else语句时, 需要牢记一些关键点。这些要点如下:
- if语句可以为零或一个else语句, 并且必须在其他if语句之后。
- if语句可以包含许多其他if语句, 它们位于else语句之前。
- 一旦else if语句成功, 将不会测试其余的if 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.
}
流程图
例子1
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")
输出
例子2
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")
}
输出
例子3
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")
}
输出
例子4
x <- c("Hardwork", "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")
}
输出
例子5
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("Largest number is =", largest)
输出
评论前必须登录!
注册