和-1的操作

发布于 2025-02-04 20:11:55 字数 343 浏览 2 评论 0原文

在代码中实施逻辑操作时,我发现了一种现象,不应在IF语句中输入它。 事实证明,这是-1和自然数的和(&&)操作。

我不知道为什么值1在下面的相同代码中打印。 我进行了直接计算,例如1的补充和2的补充,但没有1出来。

#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int b = -1;
    
    int c = a && b;
    
    printf("test = %d",c);

    return 0;
}

While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&) operation of -1 and natural numbers.

I don't know why the value 1 is printed in the same code below.
I ran direct calculations such as 1's complement and 2's complement, but no 1 came out.

#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int b = -1;
    
    int c = a && b;
    
    printf("test = %d",c);

    return 0;
}

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

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

发布评论

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

评论(1

深巷少女 2025-02-11 20:11:55

expression a&amp;&amp; bbool类型,是truefalse:它是true If an如果 ab是非零的,false否则。正如您的问题所提到的补充方案(请注意,从C ++ 20中,int始终是2的补充),-0和+0都是为零的,目的是&amp;&amp; < /代码>。

当分配给int类型c时,bool类型被隐式转换为0(如果false)或1(如果true)。

(在C中,分析相似,除了a&amp;&amp; bint类型,因此不进行隐式转换。)

The expression a && b is a bool type and is either true or false: it is true if and only if both a and b are non-zero, and false otherwise. As your question mentions complementing schemes (note that from C++20, an int is always 2's complement), -0 and +0 are both zero for the purpose of &&.

When assigned to the int type c, that bool type is converted implicitly to either 0 (if false) or 1 (if true).

(In C the analysis is similar except that a && b is an int type, and the implicit conversion therefore does not take place.)

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