c - 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个有效位
基本上数一下数里有多少个
解决方案
正如多条评论中指出的那样,它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 位整数中设置的位数?
推荐阅读
- javascript - 在类中创建函数时出现错误
- ios - 我可以关闭主线程检查器,并在关闭主线程时使用 UIKit 吗?
- eclipse - Gluon 移动字符集问题
- reactjs - 用 jest 测试时如何选择 dom
- java - 如何修复 task.getresult().getdownloadurl()
- reactjs - 需要手动刷新页面才能更新
- angular - 为不同页面重用通用布局如何根据页面的角度隐藏和显示布局
- symfony - Symfony 3.4 实体关系多对多
- python - 寻找拐点:将梯度样条连接到原始数据
- javascript - 如何在等待完成之前显示加载图标