Use recursion to convert decimal to arbitrary base (Number Conversion)

About recursion

What is recursion?

To put it bluntly, the function calls itself, and then the called function continues to call itself, which will continue in an infinite loop, unless there is something in the code that terminates the call chain.

Explain the process of recursion

Recursion requires boundary conditions, a recursive forward segment, and a recursive return segment. When the boundary conditions are not satisfied, the recursion advances; when the boundary conditions are satisfied, the recursion returns.

for example:

Solving: 4!
insert image description here

#include<stdio.h>
int f(int num);
int main()
{
    
    
  int num=4;
  printf("%d\n",f(num)); 
   return 0;
}
int f(int num)
{
    
    
   if(num==0)
      return 1;
   return num*f(num-1);
}

Convert decimal to arbitrary base by recursion

train of thought

First of all, we know that there is a characteristic of the base system above ten, which is represented by capital letters starting from 10, such as hexadecimal (1,2,3,···9,A,B,C,D,E,F) , so in the program how to solve the problem that numbers are represented by letters has become the problem we face. After solving this problem, the base number less than 10 is actually easy to deal with, because the problem of letters will not be involved.

int convert(int value,int radix)
{
    
    
   if(value/radix!=0)                                                  //边界条件
   convert(value/radix,radix);
   if(radix>10)                                                        //判断基数
   {
    
    
      if(value%radix>=10)
      {
    
    
         int temp=value%radix-10;
         char typeChange=(char)(temp+'A');
         printf("%c",typeChange);
      }
      else
      {
    
    
         printf("%d",value%radix );
      }
   }
   else
   {
    
    
      printf("%d",value%radix );
   }
   return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43349916/article/details/104622355