逻辑操作员不输出正确的结果

发布于 2025-01-20 23:35:40 字数 247 浏览 3 评论 0 原文

这是我正在努力解决的代码,

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a{ 6 }, b{ 9 };
    cout << !(a < 5) && !(b >= 7);
}

每次运行此代码时,它都会输出 1。为什么它不输出 0?

Here is the code that I'm struggling with

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a{ 6 }, b{ 9 };
    cout << !(a < 5) && !(b >= 7);
}

Every time I run this code it outputs 1. Why doesn't it output 0?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

眼眸里的那抹悲凉 2025-01-27 23:35:40

您已经被我们在 C++ 中提供的 << 运算符的语义重载绊倒了。

该运算符来自 C,专门用于对整数进行位移位。

因此,它的 优先级 低于 & & 运算符。 C++ 使用 << 运算符进行流插入并没有改变这一点。 << 将在 && 之前进行评估。

因此,

cout << !(a < 5) && !(b >= 7);

首先将 !(a<5) (true,因为 a==6)插入到流中,打印 1。然后它评估该值的返回值(对 cout 的引用),将其转换为布尔值,然后评估 && (本质上是 (!cout. fail() && !(b>=7))),丢弃结果。

您需要更多括号:

cout << (!(a < 5) && !(b >= 7));

但是,

cout << (a>=5 && b < 7);

会更清楚。

You've been tripped up by the semantic overloading we give the << operator in C++.

This operator comes from C, where it is used exclusively for bit-shifting integers.

Because of that, it has a lower precedence than the && operator. C++'s use of the << operator for stream insertion doesn't change that. The << will be evaluated before the &&.

Thus

cout << !(a < 5) && !(b >= 7);

first inserts !(a<5) (true, since a==6) into the stream, printing a 1. Then it evaluates the return value of that (a reference to cout), converts it to boolean, then evaluates the && (essentally (!cout.fail() && !(b>=7))), discarding the result.

You need more parentheses:

cout << (!(a < 5) && !(b >= 7));

However,

cout << (a>=5 && b < 7);

would be clearer.

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