进制之间转换
#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;
}