首页 > 解决方案 > C 代码在假定运行 scanf 行时停止

问题描述

考虑到输入是正确的二进制数,我编写了一个代码,该代码应该计算从用户那里获得的二进制数中有多少活动位(1)。

每次应该在 main() 中运行 scanf() 的代码都会卡住,它不会停止运行,只是感觉它在无限地思考并且没有给出任何错误

这是我写的代码,在这种情况下会打印“请输入二进制数:”然后它会卡住

#include <stdio.h>


void count_bits(long int UserNum){
    int cnt=0;
    while(UserNum>0)
    {
        if (UserNum%10==1)
        {
            cnt++;  
        }   
    }
    printf("there are %d active bits\n",cnt);
}


int main(){
    long int UserNum=0;

    printf("Please enter a binaric number: ");
    scanf("%ld" , &UserNum);
    count_bits(UserNum);
    
    return 1;
}

如果我先这样写 scanf() 它甚至不会打印:

scanf("%ld" , &UserNum);
printf("Please enter a binaric number: ");

我在这里做错了什么?

编辑:示例输入:1101100

输出:有4个有效位

输入:0110100111

输出:有6个有效位

基本上数一下数里有多少个

标签: cscanf

解决方案


正如多条评论中指出的那样,它UserNum>0始终是正确的,因此循环永远不会停止。

但无论如何,这个count_bits功能都是错误的。对位进行模 10 运算是没有意义的。

你要这个:

void count_bits(long int UserNum) {
  int cnt = 0;

  while (UserNum > 0)
  {
    if (UserNum % 2)  // if UserNum is odd, then bit no. 0 is 1
      cnt++;

    UserNum = UserNum / 2;  // division by 2 shifts bits to the right
  }

  printf("there are %d active bits\n", cnt);
}

当我们在位级别上工作时,使用位移位和位掩码操作会更惯用:

void count_bits(long int UserNum) {
  int cnt = 0;

  while (UserNum > 0)
  {
    if (UserNum & 1)    // mask all bits but bit no. 0
      cnt++;

    UserNum = UserNum >> 1;   // shift bits to the right
  }
  printf("there are %d active bits\n", cnt);
}

不过仍有改进的余地。尤其是负数将无法正常工作(虽然我没有测试,但自己找出来)。

有更复杂的方法来计算位,如下所述:如何计算 32 位整数中设置的位数?


推荐阅读