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


  • 相关阅读:
    MVC,MVP和MVVM的区别
    将数组里某个属性相同的对象合并成一个数组
    Ajax的理解
    VUE如何关闭Eslint的方法
    数组去重
    vue-router传递参数的几种方式
    密码的显示和隐藏
    "校园易借查询"选题报告
    我的第一个微信好友分析
    数据库实践
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007632.html
Copyright © 2011-2022 走看看