Julia - 三元运算符

三元运算符的格式:

a ? b : c

a 是条件表达式,如果条件 a 为真,就执行 b;如果条件 a 为假,就执行 c

二选一

julia> println(1 < 2 ? "1 is smaller than 2" : "1 is bigger than 2")
1 is smaller than 2

julia> println(1 > 2 ? "1 is smaller than 2" : "1 is bigger than 2")
1 is bigger than 2

三选一

julia> f(x, y) = println(x < y ? "x is smaller than y" : x > y ? "x is bigger than y" : "x is equal to y")
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 时才执行

julia> f(x) = (println(x); x)
f (generic function with 2 methods)

julia> 1 < 2 ? f("yes") : f("no")
yes
"yes"

julia> 1 > 2 ? f("yes") : f("no")
no
"no"

 

转载于:https://www.cnblogs.com/sch01ar/p/9527329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值