You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错TypeError: non-boolean (UInt16) used in boolean context,循环问题排查

解决TypeError: non-boolean (UInt16) used in boolean context问题

嘿,这个问题我之前也踩过坑,咱们一步步拆解原因和解决办法:

错误根源

你看到的TypeError: non-boolean (UInt16) used in boolean context,核心问题是while循环的条件必须是布尔值(true/false),但你传入了一个UInt16类型的整数。

看你的代码片段:

current_value = UInt16(6)
bit = UInt16(8)
while (current_value & bit)
    bit >>= 1
end

current_value & bit是位与运算,返回的结果是UInt16类型的数值(比如这里6和8位与的结果是0x0000,也就是十进制的0)。但你的语言(看起来是Julia)不会自动把非零整数当成true、零当成false,必须明确转换成布尔值才行。

修复方案

只需要把循环条件改成明确的布尔判断即可,有两种常用方式:

方式1:和0比较判断非零

直接判断位运算结果是否不等于0,这样会返回布尔值:

current_value = UInt16(6)
bit = UInt16(8)
while (current_value & bit) != 0
    bit >>= 1
end

方式2:用iszero()函数取反

利用iszero()函数判断结果是否为零,再取反得到布尔条件:

current_value = UInt16(6)
bit = UInt16(8)
while !iszero(current_value & bit)
    bit >>= 1
end

这两种写法都能让循环条件返回正确的布尔值,完美解决类型错误的问题。

内容的提问来源于stack exchange,提问作者Jimbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:23:37