zoukankan      html  css  js  c++  java
  • 求一个数的二进制的位数(二)

    #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...


  • 相关阅读:
    CodeForces 522B 手速题
    mybatis多数据源报错
    as依赖解决报错
    As 400错
    maven直接饮用jar包的写法
    测试一下多线程同时往list中添加元素会不会出问题
    jmeter中判断数据库是否存在相应的记录
    jmeter打开图形化界面时指定代理
    wz
    初阳胜阴
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007633.html
Copyright © 2011-2022 走看看