📌  相关文章
📜  Julia 中的决策(if、if-else、Nested-if、if-elseif-else 阶梯)

📅  最后修改于: 2021-11-25 04:44:58             🧑  作者: Mango

编程语言中的决策语句决定了程序执行流程的方向。编程语言使用控制语句根据特定条件控制程序的执行流程。这些用于根据程序状态的变化使执行流程前进和分支。 Julia 中可用的决策语句有:

  • if 语句
  • if..else 语句
  • 嵌套的 if 语句
  • if-elseif 阶梯

if 语句

if 语句是最简单的决策语句。它用于决定是否执行某个语句或语句块,即如果某个条件为真,则执行语句块,否则不执行。

语法

if condition         
   # Statements to execute if
   # condition is true
end

在这里,评估后的条件将为真或假。 if-statement 接受布尔值——如果值为真,那么它将执行它下面的语句块,否则不执行。我们可以使用带支架条件“(”“)”也。
写在if 语句end语句中的语句被认为是一个块,如果条件满足就会被执行。

流程图:-
java中的if语句

# Julia program to illustrate If statement
  
i = 10
if (i > 15)
   println("10 is greater than 15")
end
println("I am Not in if")

输出:
决策如果
在上面的代码中,if 语句中的条件为假。因此,不会执行 if 语句下方的块。

如果别的

单独的 if 语句告诉我们,如果条件为真,它将执行语句块,如果条件为假,则不会执行。但是,如果条件为假,我们想做其他事情怎么办。下面是else语句。当条件为假时,我们可以使用else语句和if 语句来执行代码块。
语法

if (condition)
    # Executes this block if
    # condition is true
else
    # Executes this block if
    # condition is false
end

流程图:-
if-else 语句

# Julia program to illustrate If-else statement
  
i = 20;
if (i < 15)
    println("$i is smaller than 15")
    println("I'm in if Block")
else
    println("$i is greater than 15")
    println("I'm in else Block")
end
println("I'm not in if and not in else Block")

其他决策

在上面的代码中,if 语句中给出的条件为假。因此,执行 else 语句中编写的代码块。之后,当 else 块的执行结束时,编译器执行写在 If-else 语句之外的语句。

嵌套如果

嵌套 if 是一个 if 语句,它是另一个 if 语句的目标。嵌套 if 语句是指写在另一个 if 语句中的 if 语句。是的,Julia 允许我们在 if 语句中嵌套 if 语句。即,我们可以将一个 if 语句放在另一个 if 语句中,依此类推,可以根据需要使用多个 if 语句。

语法

if (condition1)
   # Executes when condition1 is true
   if (condition2)
      # Executes when condition2 is true
   # if Block ends here
   end
# if Block ends here
end

流程图:-
嵌套如果

# Julia program to illustrate nested-If statement
  
i = 14
  
# First if statement
if (i == 14)
  
    # First Nested-if statement
    if (i < 15)
        println("$i is smaller than 15")
  
        # This Nested statement
        # will only be executed if 
        # the first Nested-if statement is true
        if (i < 12)
            println("$i is smaller than 12 too")
        else
            println("$i lies between 12 and 15")
        end
    else
        println("$i is greater than 15")
    end
end

输出:
决策嵌套如果

if-elseif-else 阶梯

在这里,用户可以在多个选项中做出决定。 if 语句是自上而下执行的。一旦控制 if 的条件之一为真,则执行与该 if 相关的语句,并绕过梯形图的其余部分。如果没有一个条件为真,则将执行最后的 else 语句。

语法

if (condition)
    statement
elseif (condition)
    statement
.
.
else
    statement
end

流程图:-
if-else-if-梯形图

# Julia program to illustrate if-elseif-else ladder
  
i = 20
if (i == 10)
    println("Value of i is 10")
elseif(i == 15)
    println("Value of i is 15")
elseif(i == 20)
    println("Value of i is 20")
else
    println("Value of i is not defined")
end

输出:
决策-If-elseif-else