count = count + n&1 和 count += n&1 之间的区别

Difference between count = count + n&1 and count += n&1

我正在编写一个程序,我想在其中计算整数中的集合位。 例如,如果 5 可以写为 0101,其中设置位的数量为 2。 但是,当我执行我写的程序时 count = count + n & 1 它没有用,但是如果我将其更改为 count += n&1 它工作得很好,我找不到任何理由

#include<bits/stdc++.h>
using namespace std;

int main(){
    unsigned int n = 5;
    unsigned int count = 0;
    while(n){

      //count += n&1;
        count = count + n & 1;
        n>>=1;
    }
    cout<<count;
    return 0;
}

C++ 或任何其他编程语言中的优先级决定了这些指令的求值顺序,有些是从右到左,有些先求值然后再求值。因此,在这种情况下,您的 += 是在 & (AND) 运算符之后进行评估的,这就是您在以这种方式完成时回答错误的原因

count = count + n & 1;

因为在上面的代码中,先对 + 求值,然后对 AND 求值。你可以像下面这样在它周围放一个括号

count = count + (n & 1);

由于括号运算符具有更高的优先级,它将始终确保您获得正确的结果。 您可以了解有关优先级的更多信息 here。您将看到每个运算符的评估顺序。

The associativity of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses. This affects how an expression is evaluated.

并且您可以随时查看 C++ 或 C 参考手册以了解有关优先级的更多信息。 https://en.cppreference.com/w/cpp/language/operator_precedence

Operators are evaluated from top to bottom of the list. Those at the top are evaluated first, and those below are evaluated last according to their associativity either left to right or right to left.