使用移位运算的时候,没有把最终的值重新赋值到原变量,导致死循环

来源:互联网 发布:托福app软件推荐 编辑:程序博客网 时间:2024/04/28 10:57

如下代码所示,在使用移位运算的时候,粗心地忘记了赋值运算符。应使用 tmp >>= 1 而不是 tmp >> 1。否则的话tmp一直没有被更新,造成程序陷入到死循环中。

#include <stdio.h>#include <stdlib.h>#include <assert.h>int * newIntRaw(int n){    return (int *)malloc(sizeof(int) * n);}int count(int num){    int res = 0;    unsigned int tmp = (unsigned int)num;    while (tmp) {        if (tmp & 0x1) res++;        tmp = tmp >> 1; // 或者是 tmp >>= 1 而不是 tmp >> 1    }    return res;}int * countBits(int num, int *returnSize) {    int i;    int *res = newIntRaw(num + 1);    assert(num >= 0);    *returnSize = num + 1;    for (i = 0; i <= num; ++i)        res[i] = count(i);    return res;}void dispInt(int *arr, int n){    int i;    for (i = 0; i < n; ++i)        printf("%d ", arr[i]);    putchar('\n');}int main(){    int num;    int n;    int *ret;    scanf("%d", &num);    ret = countBits(num, &n);    dispInt(ret, n);    return 0;}/*50 1 1 2 -1 2*/
阅读全文
0 0
原创粉丝点击