进制转换
#include<stdio.h> #include<stdlib.h> #define STACK_INT_SIZE 10 #define STACK_INCREMENT 2 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW 0 typedef struct SqStack{ int *base; int *top; int stacksize; }SqStack; void InitStack(SqStack *sq){ sq->base = (int *)malloc(STACK_INT_SIZE*sizeof(int)); if(!sq->base){ exit(OVERFLOW); } sq->top=sq->base; sq->stacksize = STACK_INT_SIZE; } int StackEmpty(SqStack sq){ if(sq.base == sq.top) return TRUE; else return FALSE; } int StackLength(SqStack sq){ return (sq.top-sq.base); } void Push(SqStack *sq,int e){ if(sq->top-sq->base == sq->stacksize){ sq->base = (int*)realloc(sq->base,(sq->stacksize+STACK_INCREMENT)*sizeof(int)); if(!sq->base) exit(OVERFLOW); sq->top = sq->base+STACK_INCREMENT; sq->stacksize +=STACK_INCREMENT; } *(sq->top++) = e; } int Pop(SqStack *s,int *e){ if(s->top == s->base ) return ERROR; *e = *--s->top; return OK; } void conversion_16(){ SqStack s; int n; int e; InitStack(&s); printf("将进制数转化为16进制数\n请输入n (n>0):"); scanf("%d",&n); while(n){ Push(&s,n%16); n = n/16; } while(!StackEmpty(s)){ Pop(&s,&e); if(e>9){ printf("%c",e+55); } else printf("%d",e); } printf("\n"); } void conversion_8(){ SqStack s; int n; int e; InitStack(&s); printf("将10进制数转化为8进制数\n请输入n (n>0):"); scanf("%d",&n); while(n){ Push(&s,n%8); n = n/8; } while(!StackEmpty(s)){ Pop(&s,&e); printf("%d",e); } printf("\n"); } void conversion_2(){ SqStack s; int n; int e; InitStack(&s); printf("将10进制数转化为2进制数\n请输入n (n>0):"); scanf("%d",&n); while(n){ Push(&s,n%2); n = n/2; } while(!StackEmpty(s)){ Pop(&s,&e); printf("%d",e); } printf("\n"); } int main(){ SqStack sq; InitStack(&sq); conversion_16(); conversion_8(); conversion_2(); return 0; }