从键盘获取一个short整数,计算它有多少个bit是1.
从键盘获取一个short整数,计算它有多少个bit是1.#include <stdio.h>
#include<stdlib.h>
#include<tchar.h>
#include<conio.h>
#include<string.h>
int main(void)
{
printf("请随意按键:");
short int n;
scanf_s("%d", &n);
int q = 0;
int num = 1;
int f = n;
while (q < 16)
{
if (((f = f >> q) & 1) == 1)
{
num = num + 1;
}
q++;
}
printf("该整数有%d个bit是1", num);
system("pause");
return 0;
}
我写的但是超过15就不对了。而且每次都报错Run-Time Check Failure #2 - Stack around the variable 'n' was corrupted.
[此贴子已经被作者于2016-5-23 22:39编辑过]