10进制的转换——C语言+python+C++

10进制的转换

C语言(此代码以转换二进制为例——这个为公式法)

#include
int fact(int n)
{
     
if(n<2)//将 2 换成其它数如 8 就可输出 8 进制的结果
return n;
else
{
     
return fact(n/2)*10+n%2;//将二进制结果整个输出
}
}
int main(void)
{
     
int n;
printf("enter n :  \n") ;
scanf("%d",&n);
printf("%d",fact(n));
return 0;
}

输入:10
输出:1010
10进制的转换——C语言+python+C++_第1张图片
C++(公式法)

#include 
using namespace std;
int fact(int n)
{
     
if(n<2)//将 2 换成其它数如 8 就可输出 8 进制的结果
return n;
else
{
     
return fact(n/2)*10+n%2;//将二进制结果整个输出
}
}
int main(void)
{
     
int n;
cout<<"enter n :"<<"\n" ;
cin>>n;
cout<<fact(n)<<"\n";
return 0;
}

输入:6
输出:110
在这里插入图片描述

python(栈结构)


n=int(input('请输入要转换的数值:'))
x=2  #转换为二进制时,这里取x=2
a=[]  #一个数组,存储余数
while True:   #一直循环,商为0时利用break退出循环
    s=n//x  #商
    y=n%x   #余数
    a=a+[y] #每一个余数存储到a中
    if s==0:
        break  #余数为0时结束循环
    n=s
a.reverse()  #使b中的元素反向排列
print ('该数字转换为二进制后是:',end='')
for i in a:
    print (i,end='') 

输入:7
输出:111
在这里插入图片描述
这个采取的是栈的结构,将每一次除的余数进行存储,最后进行反向排列,即是这个转换的进制的值

C语言(栈结构)

#include
#include
#include
#include
#include "process.h"
#define SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef struct
{
     
  int a;
} SElemType;
typedef struct
{
     
  SElemType *base;
  SElemType *top;
  int stacksize;
} SqStack;
SqStack S; //定义全局变量
Status InitStack(SqStack *S)
{
     
  S->base=(SElemType *)malloc(SIZE*sizeof(SElemType));
  if(!S->base) exit(OVERFLOW);
  S->top=S->base;
  S->stacksize=SIZE;
  return OK;
}
Status Push(SqStack *S,SElemType e)
{
     
  if(S->top-S->base>=S->stacksize)
  {
     
    S->base=(SElemType *)malloc((S->stacksize+STACKINCREMENT)*sizeof(SElemType));
    if(!S->base) exit(OVERFLOW);
    S->top=S->base+S->stacksize;
    S->stacksize+=STACKINCREMENT;
  }
  *S->top++=e;
  //printf("%dwww\n",*--S->top);
  return OK;
}
Status Stackempty(SqStack *S)
{
     
  if(S->top==S->base)
    return TRUE;
  else
    return FALSE;
}
Status Pop(SqStack *S,SElemType *e)
{
     
  if(S->top==S->base) return ERROR;
  *e=*--S->top;
  return OK;
}
Status DtoBTrans(int N,SqStack *S)
{
     
  SElemType e;
  while(N)
  {
     
    e.a=N%2;
    Push(S,e);
    N=N/2;
  }
  while(!Stackempty(S))
  {
     
    Pop(S,&e);
    printf("%d",e);
  }
  return OK;
}
int main()
{
     
  int x;
  InitStack(&S);
  printf("请输入十进制数:");
  scanf("%d",&x);
  DtoBTrans(x,&S);
}

输入:10
输出:1010
在这里插入图片描述

你可能感兴趣的:(笔记,python,c语言,c++,数据结构)