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

 

相关文章:

  • 2021-11-29
  • 2021-09-08
  • 2021-12-30
  • 2021-08-03
  • 2021-10-23
  • 2022-02-03
  • 2022-01-02
猜你喜欢
  • 2022-12-23
  • 2021-04-20
相关资源
相似解决方案