用链栈写进制转换
将十进制整数转换为r进制数,其转换方法为辗转相除法。用链栈实现
/*将十进制整数转换为r进制数,其转换方法为辗转相除法。用链栈实现 time 2019/10/13 */ #include<stdio.h> #include<stdlib.h> #include<conio.h> typedef int datatype; typedef struct node { datatype data; struct node *next; }*linkstack; //入栈 int Push(linkstack *top,datatype x) { linkstack s = (linkstack)malloc(sizeof(struct node)); if(s==NULL) return 0; s->data = x; s->next = (*top); (*top) = s; return 1; } //判空 int Empty(linkstack top) { if(top==NULL) return 1; return 0; } //出栈 int Pop(linkstack *top, datatype *x) { if(top!=NULL) { linkstack p = (*top); (*x) = (*top)->data; (*top) = (*top)->next; free(p); return 1; } return 0; } //十进制整数转化为任意进制数 void Convert(int num,int mode) { int h; linkstack top = NULL; printf("转化结果为空:"); if(num>0) { while(num!=0) { h=num%mode; Push(&top,h); num=num/mode; } while(!Empty(top)) { Pop(&top,&h); printf("%d",h); } printf("\n"); } else if(num<0) { printf("-"); num = num*(-1); while(num!=0) { h=num%mode; Push(&top,h); num=num/mode; } while(!Empty(top)) { Pop(&top,&h); printf("%d",h); } printf("\n"); } else printf("%d\n",0); } void main() { int num , mode; printf("\n 输入要转化的数:"); scanf("%d",&num); printf("输入要转化的进制:"); scanf("%d",&mode); Convert(num,mode); }