7, the decimal number into a binary number

Title: convert decimal numbers to binary numbers

Available for 15 and less than a decimal number:

#include<stdio.h>
void fun(int n);
int main(){
	int n;
	scanf("%d", &n);
	fun(n);
	return 0;
}

void fun(int n){
	int a[4], i;
	//十进制数不断除2,余数保存在数组中(容量为4的数组即4位二进制数能表示的最大数为15)
	for(i=0;i<4;i++){
		a[i]=n%2;
		n = n/2;
	}
	//从后往前,遍历数组输出二进制(数组的最后一个元素是二进制的最高位)
	for(i=3;i>=0;i--){
		printf("%d", a[i]);
	}
	printf("\n");
}

31 and modified to apply to a decimal number less than:

void fun(int n){
	int a[5], i;
	//5位二进制数能表示的最大数为31
	for(i=0;i<5;i++){
		a[i]=n%2;
		n = n/2;
	}
	for(i=4;i>=0;i--){
		printf("%d", a[i]);
	}
	printf("\n");
}

Similarly, to express more decimal, that is simply changing the size of the array capacity-digit binary number can be.

Published 16 original articles · won praise 0 · Views 326

Guess you like

Origin blog.csdn.net/NAU_LHT/article/details/104168131