逻辑运算符 #

一、基本逻辑运算符 #

1.1 运算符列表 #

运算符 描述 示例
! 逻辑非 !true
&& 逻辑与 true && false
` `

1.2 基本运算 #

julia
!true
!false
true && true
true && false
false && true
false && false
true || true
true || false
false || true
false || false

1.3 真值表 #

与运算 (&&):

A B A && B
true true true
true false false
false true false
false false false

或运算 (||):

A B A || B
true true true
true false true
false true true
false false false

二、短路求值 #

2.1 && 短路 #

&&在第一个操作数为false时短路:

julia
false && println("This won't print")
true && println("This will print")

2.2 || 短路 #

||在第一个操作数为true时短路:

julia
true || println("This won't print")
false || println("This will print")

2.3 条件执行 #

使用短路求值进行条件执行:

julia
x = 5
x > 0 && println("Positive")
x < 0 || println("Non-negative")

2.4 默认值 #

julia
name = nothing
actual_name = name || "Anonymous"

三、位运算符 #

3.1 运算符列表 #

运算符 描述 示例
~ 按位非 ~0b1010
& 按位与 0b1010 & 0b1100
| 按位或 0b1010 | 0b1100
按位异或 0b1010 ⊻ 0b1100
>>> 逻辑右移 0b1000 >>> 2
>> 算术右移 0b1000 >> 2
<< 左移 0b0010 << 2

3.2 基本位运算 #

julia
~0b1010
0b1010 & 0b1100
0b1010 | 0b1100
0b1010 ⊻ 0b1100
0b1000 >>> 2
0b1000 >> 2
0b0010 << 2

3.3 位运算应用 #

julia
x = 0b1010
x & 0b1000
x | 0b0100
x ⊻ 0b1111

四、逻辑函数 #

4.1 any 和 all #

julia
any([false, false, true])
any([false, false, false])
all([true, true, true])
all([true, false, true])

4.2 条件函数 #

julia
arr = [1, 2, 3, 4, 5]
any(x -> x > 3, arr)
all(x -> x > 0, arr)

4.3 count #

julia
arr = [1, 2, 3, 4, 5]
count(x -> x > 3, arr)
count(x -> x % 2 == 0, arr)

五、三元运算符 #

5.1 基本语法 #

julia
condition ? value_if_true : value_if_false

x = 5
x > 0 ? "Positive" : "Non-positive"

5.2 嵌套三元 #

julia
x = 0
x > 0 ? "Positive" : x < 0 ? "Negative" : "Zero"

5.3 与if-else对比 #

julia
x = 5

result = x > 0 ? "Positive" : "Non-positive"

result = if x > 0
    "Positive"
else
    "Non-positive"
end

六、实践练习 #

6.1 练习1:条件执行 #

julia
function safe_divide(a, b)
    b != 0 && return a / b
    return nothing
end

safe_divide(10, 2)
safe_divide(10, 0)

6.2 练习2:验证 #

julia
function validate_age(age)
    age >= 0 || error("Age cannot be negative")
    age <= 150 || error("Age seems unrealistic")
    return true
end

validate_age(25)
validate_age(-1)

6.3 练习3:默认值 #

julia
function greet(name)
    actual_name = name === nothing ? "Guest" : name
    println("Hello, $actual_name!")
end

greet("Julia")
greet(nothing)

6.4 练习4:位掩码 #

julia
const READ = 0b100
const WRITE = 0b010
const EXECUTE = 0b001

function has_permission(permissions, flag)
    (permissions & flag) != 0
end

perms = READ | WRITE
has_permission(perms, READ)
has_permission(perms, EXECUTE)

七、总结 #

本章我们学习了:

  1. 基本逻辑运算:!、&&、||
  2. 短路求值:条件执行和默认值
  3. 位运算符:~、&、|、⊻、>>、<<
  4. 逻辑函数:any、all、count
  5. 三元运算符:条件表达式

接下来让我们学习Julia的控制流!

最后更新:2026-03-27