C语言日常小练习-1.5

1.写一个函数返回参数二进制中 1 的个数
   比如: 15 0000 1111 4 个 1

#include <stdio.h>
#include <Windows.h>

int count_one(unsigned int value)
{
	int count = 0;
	while (value)
	{
		if (value % 2 == 1)
		{
			count++;
		}
		value = value / 2;//右移一位
	}
	return count;
}

int count_two(unsigned int value)
{
	int count = 0;
	while (value)
	{
		count++;
		value = value & (value - 1);
	}
	return count;
}

int main() {
	
	int count_1 = count_one(15);
	int count_2 = count_two(15);

	printf("对应二进制中 1 出现的次数:\n%d\n", count_1);
	printf("对应二进制中 1 出现的次数:\n%d\n", count_2);

	system("pause");
	return 0;

}

2.获取一个数的二进制序列中所有的偶数位和奇数位,分别输出二进制序列。

#include <stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)


void get_value() {

	int value = 0;
	printf("请输入数字:");
	scanf("%d", &value);
	int a[32];
	int i = 0;

	for (i = 0; i < 32; i++){
		a[i] = value % 2;
		value /= 2;
	}

	printf("偶数:");
	for (i = 31; i >= 0; i -= 2){
		printf("%d", a[i]);
	}
	printf("\n");

	printf("奇数:");
	for (i = 30; i >= 0; i -= 2){
		printf("%d", a[i]);
	}
	printf("\n");
}
int main(){
	get_value();
	
	system("pause");
	return 0;
}

3. 输出一个整数的每一位。 

#include <stdio.h>
#include <Windows.h>
#pragma warning(disable:4996)

void play(int x){
	
	if (x != 0)
	{
		printf("%d", x % 10);
		play(x / 10);
	}
	printf("\n");
}

int main()
{
	int x;
	printf("请输入整数:");
	scanf("%d", &x);
	play(x);

	system("pause");
	return 0;

}

4.编程实现: 
两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同? 
输入例子: 
1999 2299 

输出例子:7 

#include<stdio.h>
#include<Windows.h>
int main()
{
	int u = 0;
	int m = 0;
	int n = 0;
	int count = 0;
	printf("请输入两个数:\n");
	scanf_s("%d %d", &m, &n);
	u = m ^ n;  //m和n异或
	while (u)   //相当于找出一个数;二进制中1的个数
	{
		count++;
		u = u & (u - 1);
	}
	printf("count=%d", count);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39026129/article/details/80197733