当把余数全部进栈后,如何获得最后的进制数
方法1:直接一个一个输出
方法2:
| ||||
数制转换核心代码
|
/*
123
二进制:1111011
八进制:173
十六进制:7B
*/
#include<stdio.h>
#include<malloc.h>
typedef unsigned char boolean;
#define TRUE 1
#define FALSE 0
typedef int dataType;
#define MAXSIZE 100
typedef struct{
dataType *data;
int maxSize;
int top;
}SeqStack;
static char *CHARACTERS = "0123456789ABCDEF";
boolean initStack(SeqStack **s);
void destroyStack(SeqStack **s);
boolean push(SeqStack *s, dataType x);
boolean isStackFull(SeqStack s);
boolean isStackEmpty(SeqStack *stack);
boolean getTop(SeqStack *stack, dataType *x);
boolean pop(SeqStack *stack, dataType *x);
void showData(SeqStack s);
void convertNumber(dataType n, int d);
void convertNumber(dataType n, int d){
SeqStack *s = NULL;
dataType tmp = n;
initStack(&s);
while(tmp){
push(s, tmp%d);
tmp/=d;
//printf("tmp=%d\n", tmp);
}
printf("原数为:%d,%d进制数为:", n, d);
showData(*s);
destroyStack(&s);
}
/*
void showData(SeqStack s){
int i;
for(i = 0; i < s.top+1; i++){
printf("%d", s.data[i]);
}
printf("\n");
}
*/
/*
//上一个出现一个小问题,输出时应该从上往下输
void showData(SeqStack s){
int i;
for(i = s.top; i > -1; i--){
printf("%d", s.data[i]);
}
printf("\n");
}
*/
/*
//上一个出现一个小问题:16进制时余数要用ABCDEF表示
void showData(SeqStack s){
int i;
for(i = s.top; i > -1; i--){
//printf("%d", CHARACTERS[s.data[i]]);
printf("%c", CHARACTERS[s.data[i]]);
}
printf("\n");
}
*/
//实验书上的思想
void showData(SeqStack s){
dataType x;
while(! isStackEmpty(&s)){
//printf("%d", CHARACTERS[s.data[i]]);
pop(&s, &x);
printf("%c", CHARACTERS[x]);
}
printf("\n");
}
boolean pop(SeqStack *stack, dataType *x){
if(isStackEmpty(stack)){
return FALSE; //栈空,如法出栈
}
*x = stack->data[stack->top--];
return TRUE;
}
boolean getTop(SeqStack *stack, dataType *x){
if(isStackEmpty(stack)){
return FALSE; //栈空
}
*x = stack->data[stack->top];
return TRUE;
}
boolean isStackEmpty(SeqStack *stack){
return stack->top == -1;
}
boolean isStackFull(SeqStack s){
return s.top == s.maxSize-1;
}
boolean push(SeqStack *s, dataType x){
if(isStackFull(*s)){
return FALSE;
}
s->data[++s->top] = x;
return TRUE;
}
void destroyStack(SeqStack **s){
free((*s)->data);
free(*s);
*s = NULL; //s = NULL;
}
boolean initStack(SeqStack **s){
if(*s != NULL){
return FALSE;
}
*s = (SeqStack *)malloc(sizeof(SeqStack));
(*s)->data = (dataType *)malloc(sizeof(dataType) * MAXSIZE);
(*s)->maxSize = MAXSIZE;
(*s)->top = -1;
return FALSE;
}
void main(void){
dataType n;
int d;
printf("请输入一个正整数:");
scanf("%d", &n);
printf("请输入进制:");
scanf("%d", &d);
convertNumber(n, d);
}