逻辑操作员不输出正确的结果
这是我正在努力解决的代码,
#include <iostream>
#include <string>
using namespace std;
int main() {
int a{ 6 }, b{ 9 };
cout << !(a < 5) && !(b >= 7);
}
每次运行此代码时,它都会输出 1。为什么它不输出 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经被我们在 C++ 中提供的
<<
运算符的语义重载绊倒了。该运算符来自 C,专门用于对整数进行位移位。
因此,它的 优先级 低于
& &
运算符。 C++ 使用<<
运算符进行流插入并没有改变这一点。<<
将在&&
之前进行评估。因此,
首先将
!(a<5)
(true,因为a==6
)插入到流中,打印1
。然后它评估该值的返回值(对cout
的引用),将其转换为布尔值,然后评估&&
(本质上是(!cout. fail() && !(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
first inserts
!(a<5)
(true, sincea==6
) into the stream, printing a1
. Then it evaluates the return value of that (a reference tocout
), converts it to boolean, then evaluates the&&
(essentally(!cout.fail() && !(b>=7))
), discarding the result.You need more parentheses:
However,
would be clearer.