【问题标题】:What does this C function return?这个 C 函数返回什么?
【发布时间】:2013-01-09 18:26:53
【问题描述】:
int f(int n)
{
    int i, c = 0;
    for (i=0; i < sizeof(int)*8; i++, n >>= 1)
        c = (n & 0x01)? c+1: c;
    return c;
}

这是我在书上找到的一个练习,但我真的不明白!

【问题讨论】:

  • 您对哪个具体部分有疑问?
  • 它返回一个int。确切的值取决于传递给函数的参数。
  • @CarlNorum,我不明白这部分的作用:c​​ = (n & 0x01)? c+1: c;
  • 要弄清楚这一点,请查看函数的每个部分并确保您理解它。该函数非常简单,您可以在一张纸上“运行”它,这应该有助于您理解。
  • @user1100421,我在下面的回答中解决了这个问题。

标签: c function return


【解决方案1】:

它计算传入参数n 中设置的位数(假设您的机器有 8 位字节)。我将在您的代码中内嵌注释(并修复糟糕的格式):

int f(int n)
{
    int i;     // loop counter
    int c = 0; // initial count of set bits is 0

    // loop for sizeof(int) * 8 bits (probably 32), 
    // downshifting n by one each time through the loop
    for (i = 0; i < sizeof(int) * 8; i++, n >>= 1) 
    {
        // if the current LSB of 'n' is set, increment the counter 'c',
        // otherwise leave it the same
        c = (n & 0x01) ? (c + 1) : c;  
    }

    return c;  // return total number of set bits in parameter 'n'
}

【讨论】:

    【解决方案2】:

    它正在按位执行 - 打开位关闭和关闭位。

    【讨论】:

    • 不,它不是这么做的。
    • 按位“与”运算不会“打开位关闭和关闭位打开”。这是一个“非”操作。
    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多