将一个无符号十进制数转换成N(2-36)进制

//功能:将一个无符号十进制数转换成N(2-36)进制
#include <stdlib.h>
#include <stdio.h>
//定义一个新的栈数据结构
typedef struct L_stack
{
char m;
 struct L_stack *pre,*top;
}L_stack,*PL_stack;

//初始化栈
void Init(PL_stack L)
{
 L->pre=NULL;
 L->top=NULL;
}
//入栈操作
void push(L_stack * L,char element)
{
 PL_stack pt;
 pt=(PL_stack)malloc(sizeof L_stack);
 if(pt==NULL)
 {
  printf("没有足够的内存\n");
  exit(0);
 }
 pt->m=element;
 pt->pre=L->top;
 L->top=pt;
}
//退栈操作
void pop(L_stack *L)
{
 printf("%c",L->top->m);
 L->top=L->top->pre;
}

int isEmpty(L_stack *L)
{
 if(L->top==NULL)
 {
  return 0;
 }
 else
 {
  return 1;
 }
}

void main()
{
 static char digits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M',
  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
 double number;
 unsigned long integer;
 int base;
 float decimal;
 L_stack a;
 Init(&a);
 printf("请输入一个无符号十进制整数或小数:");
 scanf("%lf",&number);
 decimal=number-(int)(number);
 integer=(long)(number);
 printf("请输入需要转到的进制N(2-36):");
 scanf("%ld",&base);
 if(base<2||base>36)
 {
  printf("错误\n"); 
  exit(0);
 }
 //处理整数部分
 while(integer)
 {
  push(&a,digits[integer%base]);
  integer/=base;
 }
 
 while(isEmpty(&a))
 {
  pop(&a);
 }
 printf(".");
 //处理小数部分
 while (decimal>0.00000001)
  {
   decimal*=base;
   printf("%c",digits[(int)(decimal)]);
   if((int)(decimal)*base>(base-1))
   {
   decimal-=((int)(base-1));
   }
  }
 printf("\n");
 getch();
}
文章标签: 

引用地址:http://www.biaodianfu.com/oct-to-base.html

该日志还没有评论。

发表评论




想让您的头像与众不同,请注册Gravatar