gpt4 book ai didi

julia - 为什么 Julia 不在条件中打印 `false`?

转载 作者:行者123 更新时间:2023-12-03 23:03:22 24 4
gpt4 key购买 nike

Julia 1.4.2
难倒我的行为发生在第一种和第四种情况:

julia> if (val = (1 == 2))
println(val)
end

julia> if (val = (1 == 1))
println(val)
end
true

julia> if (val = (1 == 1))
println(val + 5)
end
6

julia> if (val = (1 == 2))
println(val + 5)
end

julia> 1 == 2
false

julia> 1 == 1
true

julia> println(1==2)
false

julia> println(1==1)
true
我在 REPL 和 Jupyter 中观察到了这一点。
我的问题是:
  • 为什么会发生这种情况?
  • 如何检索 val 的值,最好是“真实”值,在这两种情况下?
  • 最佳答案

    让我们更详细地看一下第一个示例

    # initially, `val` does not exist
    julia> val
    ERROR: UndefVarError: val not defined

    # 1==2 is false
    # the assignment returns the value of the right-hand side -> false
    julia> if (val = (1 == 2))
    # therefore, this branch is not taken
    println(val)
    else
    # but this one is
    println("in the else clause")
    end
    in the else clause

    # `if` returns whatever the branch taken evaluates to.
    # In this case, `println` returns nothing, so the `if` block does not
    # return anything either
    julia> @show ans
    ans = nothing

    # `if` doesn't introduce a new scope, so the newly created `val` variable
    # can still be inspected
    julia> val
    false

    关于julia - 为什么 Julia 不在条件中打印 `false`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64186182/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com