Recursive Algorithm 4-Simple Recursive Number System Conversion

Use recursive functions to convert decimal to binary integer

【analysis】

Divide by two and take the remainder method, constantly divide the quotient as the new dividend by 2, and the sequence of the remainder each time is the desired binary number.

When num==0, the recursion phase ends, and the recursion starts and returns; otherwise, the quotient is used as the new dividend, that is, the function is called and the remainder of each layer is output.

code:

#include<stdio.h>
#include <iostream>
void DectoBin(int num);
void main()
{
	int n;
	printf("请输入一个十进制整数:");
	scanf("%d", &n);
	printf("二进制数是:");
	DectoBin(n);
	printf("\n");
	system("pause");
}
void DectoBin(int num)
{
	if (num == 0)
		return;
	else
	{
		DectoBin(num / 2);
		printf("%d", num % 2);
	}
}

result:


 

Guess you like

Origin blog.csdn.net/baidu_36669549/article/details/104136990