求一个数的二进制的位数(二)

#include <stdio.h>

int main(void)
{
	unsigned int x;
	unsigned char ch = 'Y';
	unsigned char test_num = 0;	//count the test numbers
		
	puts("Please input the number (between 0 and 65535, which of them are included) you want to test:");
	
	while('Y' == ch)
	{
		if(test_num)
			printf("again now...\n"
			"enter the number:\n");
		scanf("%ud",&x);
		getchar();
		unsigned int temp = x;
		int ret = 0;
		
		for(; temp; temp&=(temp-1))
		{
			ret++;
		}
		
		printf("There %s %d '1'%s in the num %d\n",(ret>1)?"are":"is",ret,(ret>1)?"s":"",x);
		test_num++;
		printf("No %d tested number.\n",test_num);
		printf("-----------------------------------\n");
		puts("want ot again? Y to continue, N to finish:");		
		scanf("%c",&ch);
	}
	
	puts("Bye...");
	
	return 0;
}

测试结果:

G:\desktop\huiwenTest>bits.exe
Please input the number (between 0 and 65535, which of them are included) you want to test:
256
There is 1 '1' in the num 256
No 1 tested number.
-----------------------------------
want ot again? Y to continue, N to finish:
Y
again now...
enter the number:
369
There are 5 '1's in the num 369
No 2 tested number.
-----------------------------------
want ot again? Y to continue, N to finish:
Y
again now...
enter the number:
512
There is 1 '1' in the num 512
No 3 tested number.
-----------------------------------
want ot again? Y to continue, N to finish:
Y
again now...
enter the number:
511
There are 9 '1's in the num 511
No 4 tested number.
-----------------------------------
want ot again? Y to continue, N to finish:
Y
again now...
enter the number:
65535
There are 16 '1's in the num 65535
No 5 tested number.
-----------------------------------
want ot again? Y to continue, N to finish:
N
Bye...


posted @ 2012-07-09 17:48  wdliming  阅读(92)  评论(0编辑  收藏  举报