Java 中的表达式 (!b) 和 (b==false) 等价吗?

发布于 2024-12-12 14:33:36 字数 529 浏览 4 评论 0原文

假设 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别低头,皇冠会掉 2024-12-19 14:33:36

是的,但是好的风格要求使用 !b 而不是 b == false

yes, but good style mandates using !b rather than b == false

那一片橙海, 2024-12-19 14:33:36

是的,它们在“理智”的语言中是等价的:-)(比如 Java、C++、C#)

在 Javascript 中,如果 b 只能为 truefalse,它是正确的(但要注意!if (!null) 为 true,if (null == false) 为 false。对于未定义也是如此)

请注意并非所有语言都使用 ! 表示 NOT,使用 == 表示 EQUALS。例如,在 C 中,您可能会使用 int 代替 boolFALSE 代替 false,但结果会相同(但请注意,在 C 中,非零为“true”)

Yes, they are equivalent in "sane" languages :-) (let's say Java, C++, C#)

In Javascript if b can only be true or false, it is correct (but beware! if (!null) is true, if (null == false) is false. The same for undefined)

Be aware that not all languages use ! for NOT and == for EQUALS. For example in C you would probably use int instead of bool and FALSE instead of false, but the result would be the same (but note that in C, non-zero is "true")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文