5

我编写了一个比较 2 个两位无符号整数的新程序。通过汉明距离进行比较。但是我的算法并不完美。你能告诉我这段代码有什么问题吗:(非常感谢!!

这是我的计数方法;

int countHammDist(unsigned int n, unsigned int m)
{
int i=0;
unsigned int count = 0 ;
for(i=0; i<8; i++){
if( n&1 != m&1 ) {
    count++;
    }
n >>= 1;
m >>= 1;

}
return count;
}

a 和 b 8 位二进制文​​件。

 PrintInBinary(a);
 PrintInBinary(b);

 printf("\n %d", countHammDist(a,b));

让我告诉你输出;

Enter two unsigned integers (0-99): 55 64
Your choices are 55 and 64
Number A: 00110111
Number B: 01000000
Hamming distance is ; 5
4

2 回答 2

8

Put parantheses around n&1 and m&1.

if ((n&1) != (m&1))

http://ideone.com/F7Kyzg

This is because != is before &: http://www.swansontec.com/sopc.html

于 2013-11-06T23:50:56.363 回答
2

您也需要移位m以比较正确的位。

无论相等性测试是否通过,您都需要转移它们。(将班次移到内部}

于 2013-11-06T23:07:39.723 回答