c代码实现进制之间的转换

进制之间转换

#include<stdio.h>
#define STACKINCREMENT  10
#define ERROR;

typedef struct{
  int *base;
  int *top;
  int stacksize;
}stack;
stack S;
void initstack(){
  S.base=(int *)malloc(100*sizeof(int ));
  if(!S.base) return ERROR;
  S.top=S.base;
  S.stacksize=100;
}

void push(int e){
  if(S.top-S.base>=S.stacksize){
  S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(int ))if(!S.base) return ERROR;
  S.top=S.base+S.stacksize;
  S.stacksize+=STACKINCREMENT;
}
 *S.top=e;
  S.top++;
}

int pop(){
  int e;
  if(S.top==S.base) return ERROR;
  S.top--;
  e=*S.top;
  return e;
}

stackempty(){
if(s.base==s.top)
{return TURE;}
else
{return FALSE;}}

main(){
int n,d,e;
initstack();
scanf("%d%d",&n,&d);
while(n!=0){
push(n%d);n=n/d;}
while(!stackempty()){
e=pop();printf("%d",e);}}

任意进制转换代码:

#include<stdio.h>
#include<stdlib.h>

#define STACK_INIT_SIZE 100 
#define STACKINCRRMENT 10 

#define ok        1
#define error    0
#define Status int

typedef struct
{  
    int *base; 
    int *top; 
    int stacksize; 
} spstack;

Status Initstack(spstack *s)
{
    s->base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
    if (!s->base)
        exit(1); 
    s->top = s->base;
    s->stacksize = STACK_INIT_SIZE;
    return ok;
}


int Pop(spstack *s)
{
    int e;
    if(s->top==s->base)
        return error;
    e=*(--s->top);
    return e;
}


Status push(spstack *s, int e)
{
    if(s->top-s->base >= s->stacksize) 
    {
        s->base = (int*)realloc(s->base, (s->stacksize+STACKINCRRMENT)*sizeof(int));
        if (!s->base)
            exit(0);
        s->top = s->base + s->stacksize;
        s->stacksize += STACKINCRRMENT;
    }
    *s->top++=e;
    return ok;
}


void conversion(int p, int n, spstack *s)
{ 
    int m;

    Initstack(s);
    do
    {
        push(s, p%n);
        p = p / n;
    } while (p);
    while (s->base != s->top)
    {
        m = Pop(s);
        if (m < 10)
            printf("%d", m);
        else
            printf("%c", m-10+'A');
    }
}

 

int main()
{
    int p, n;
    spstack s;

    printf("输入要转换成?进制:\n");
    scanf("%d", &n);
    getchar();
    printf("输入要转换的进制数:\n");
    scanf("%d", &p);
    conversion(p, n, &s);
 putchar('\n');

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值