“cnt + = num%2;”和“if(num%2)++ cnt;”之间的区别

时间:2018-03-07 14:47:52

标签: c binary global-variables

“cnt + = num%2;”和“if(num%2)++ cnt;”之间的区别 我成功地计算了二进制数中的'1'的数量。 但似乎做同样事情的一条线会产生不同的结果。

全局变量“cnt = 0”被声明为代码的顶部

#include<stdio.h>
int cnt=0;

//and the recursive function which counts '1' is here
int one( int num ) {
if (num < 2)
{
 cnt += num;
  return cnt ;   //here, escape and return cnt to main. 
}                      
else
    {
        one(num / 2);
        cnt += num % 2; //according to the remainders cnt++ AND THIS IS THE THE QUESTION CORE
    }
}

void main() {
    int num;
    scanf("%d", &num);

    cnt=one(num);  //call recursive function
    printf("%d", cnt);  //and here, i want to watch the [RESULT]
}//main

[结果]

当我使用“cnt += num % 2;”打印正确答案时 但另一个看似相同的代码“if (num % 2) ++cnt;”打印错误答案。

num%2必须为0或1.因此它将“1”添加到cnt。但第二个代码不起作用。

我错过了哪一点?

1 个答案:

答案 0 :(得分:0)

除了return中缺少else branch之外,您使用全局变量cnt的方式不合适(这些都是您错过的)。以下代码效果很好:

int one(int num) {
    if (num < 2) {
        return num;
    } else {
        return (num % 2) + one(num / 2);
    }
}

希望有所帮助。

相关问题