Java 中的表达式 (!b) 和 (b==false) 等价吗?
假设 b 是布尔变量,表达式 (!b) 和 (b==false) 相同吗?
到目前为止,我对这个问题的态度是:
!b -- 返回 [如果 b 为真,则返回 FALSE 响应] 或 [如果 b 为 true,则返回 [TRUE 响应] b 为 false]。
在本例中声明一个布尔变量“b”,会将其设置为 true,因此使 !b 返回 false。
我想完成这个问题我需要做的就是知道 b 最初是否为真,我假设它是真的?
希望这是有道理的,有人可以帮我解决这个问题吗?
编辑: 这是我的导师提出的问题。我被要求判断这个说法是真是假: “表达式 (!b) 和 (b==false) 是等价的,其中 b 是布尔变量”
当我寻求帮助时,这里是非常有用的神秘线索:
!b 的情况是这些表达式应该提供为了使陈述正确,b 的所有值都会得到相同的结果。即,如果 b 为假,则两个表达式给出相同的结果,如果 b 为真,则两个表达式给出相同的结果。您需要查看这两种表达方式。
Given that b is a boolean variable, are the expressions (!b) and (b==false) the same?
Here's where I'm at so far with this question:
!b -- returns a [FALSE response if b is true] or a [TRUE response if
b is false].Declaring a boolean variable, 'b', in this case, would set it to
true, therefore making !b return false.
I suppose all I need to complete the question is to know whether or not b is initially true, which I assume it to be?
Hopefully this makes sense and someone can clear this up for me?
EDIT:
This is a question from my tutor. I am asked to decide if this statement is true or false:
"The expressions (!b) and (b==false) are equivilaent, where b is a boolean variable"
Here is here extremelly helpful cryptic clue when I asked for some help:
The situation with !b is that these expressions should provide the same result for all values of b in order for the statement to be correct. Ie if b is false, then both expressions give the same result and if b is true then both expressions give the same result. You need to look at both expressions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,但是好的风格要求使用
!b
而不是b == false
yes, but good style mandates using
!b
rather thanb == false
是的,它们在“理智”的语言中是等价的:-)(比如 Java、C++、C#)
在 Javascript 中,如果
b
只能为true
或false
,它是正确的(但要注意!if (!null)
为 true,if (null == false)
为 false。对于未定义
也是如此)请注意并非所有语言都使用
!
表示NOT
,使用==
表示EQUALS
。例如,在 C 中,您可能会使用int
代替bool
和FALSE
代替false
,但结果会相同(但请注意,在 C 中,非零为“true”)Yes, they are equivalent in "sane" languages :-) (let's say Java, C++, C#)
In Javascript if
b
can only betrue
orfalse
, it is correct (but beware!if (!null)
is true,if (null == false)
is false. The same forundefined
)Be aware that not all languages use
!
forNOT
and==
forEQUALS
. For example in C you would probably useint
instead ofbool
andFALSE
instead offalse
, but the result would be the same (but note that in C, non-zero is "true")