程序不扫描数字149,对于任何其他数字,它返回0 [关闭]

问题描述 投票:-3回答:1

我的程序应该扫描一定数量(unsigned long int)并返回其奇数'打开'索引位(来自数字的二进制表示)。但程序没有识别任何数字,只返回0,或者根本不响应该数字。我究竟做错了什么 ?

这是功能:

int count_odd_bits(unsigned long int x) {

    int count = 0;
    while (x) {
        if ((x % 2 == 1) && (x & 1))
            count++;
        else
            x = x << 1;

    }
    return count;
}

这是主要功能:

int main() {

    unsigned long int x;
    printf("\n enter a number: \n");
    scanf("%ul", &x);
    int count_odd_bits(unsigned long int x);
    printf("\n the result is:%d \n",count_odd_bits(x));

    return 0;
}

对于数字149,它应该返回1(仅打开第7位)

c
1个回答
2
投票

在函数中,当x为真时,您不会更改if。所以你最终会陷入无休止的循环中。

int count_odd_bits(unsigned long int x) {

    int count = 0;
    while (x) {
        if ((x % 2 == 1) && (x & 1))
            count++;                     // x not changed --> endless loop!!
        else
            x = x << 1;

    }
    return count;
}

此外,你似乎需要x = x >> 1;而不是当前的代码。

你也不需要x % 2 == 1x & 1,因为它们是相同的。

所以计算一个数的代码可以是:

int count_odd_bits(unsigned long int x) {

    int count = 0;
    while (x) {
        if (x & 1) count++;
        x = x >> 1;
    }
    return count;
}

如果你只想计算奇数位的位置呢

int count_odd_bits(unsigned long int x) {

    int count = 0;
    x = x >> 1;     // get rid of bit zero
    while (x) {
        if (x & 1) count++;
        x = x >> 2;    // shift by 2 to get 1->3->5->....
    }
    return count;
}
© www.soinside.com 2019 - 2024. All rights reserved.