Julia - If 条件语句

Julia 中使用 if,elseif,else 进行条件判断

格式:

if expression1
	statement1
elseif expression2
	statement2
else
	statement3
end

如果条件 expression1 成立,则执行语句 statement1

如果条件 expression2 成立,则执行语句 statement2

如果条件 expression1 和条件 expression2 都不成立,则执行语句 statement3

elseif 和 else 是可选的

elseif 可以有多个,但是 else 只能有一个

julia> function f(x, y)
           if x < y
               println("x is smaller than y")
           elseif x > y
               println("x is bigger than y")
           else
               println("x is equal to y")
           end
       end
f (generic function with 1 method)

julia> f(1, 2)
x is smaller than y

julia> f(2, 1)
x is bigger than y

julia> f(1, 1)
x is equal to y

条件表达式的值只能是 true 和 false,不能用 0 和 1 代替

julia> if true
           println("True")
       end
True

julia> if 1
           println("True")
       end
ERROR: TypeError: non-boolean (Int64) used in boolean context
Stacktrace:
 [1] top-level scope at none:0

julia> if false
           println("False")
       end

julia> if 0
           println("False")
       end
ERROR: TypeError: non-boolean (Int64) used in boolean context
Stacktrace:
 [1] top-level scope at none:0

 

posted @ 2018-08-23 22:12  Sch01aR#  阅读(1313)  评论(0编辑  收藏  举报