有人能解释一下为什么在比较两个数字的最低有效位时会有不同的输出吗?
在第一种情况下,我直接比较它们
在第二种情况下,我将LSB分配给其他变量

        //Program to check Least significant bits of two numbers
        #include<stdio.h>
            int main(){

                //LSB means least significant bit of the binary number
                //(i.e.,Unit place digit in binary number)
                //Example..... 2 = 10(in binary) and 9 = 1001(in binary)
                //so least significant bit is 0 for 2 and 1 for 9

               //In binary M =101 and LSB of M = 1
               int M = 5;
               //In binary P = 011 and LSB of P  = 1
               int P = 3;

               //printing LSB values
               printf("\nLeast significant bits are for M : %d and for P : %d",M&1,P&1);

               //Comparing LSB of M and LSB of P
               if(M&1 != P&1) {
                   printf("\nLeast significant bits are not equal");
               }
               else printf("\nLeast significant bits are equal");

               //Assigning Least significant bit of M to MLSB
               int MLSB = M&1;
               //Assigning Least significant bit of P to PLSB
               int PLSB = P&1;

               //printing LSB values
               printf("\nValue in MLSB : %d and Value in PLSB : %d",MLSB,PLSB);

               //Comparing MLSB and PLSB
               if(MLSB != PLSB) {
                   printf("\nLeast significant bits are not equal");
               }
               else printf("\nLeast significant bits are equal");


            }

输出:
最低有效位用于M:1和P:1
最低有效位不相等
MLSB:1和PLSB:1中的值
最低有效位相等

最佳答案

试着改变这个

if(M&1 != P&1) {

进入之内
if((M&1) != (P&1)) {

然后检查运算符的优先级,例如此处https://en.cppreference.com/w/c/language/operator_precedence

关于c - 编码:谁能解释我为什么比较两个数字的最低有效位时会有不同的输出?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51779845/

10-11 21:19