栈的应用,进制转换问题
算法很简单,除X取余法,用栈来把余数存起来,再出栈即可
上代码…
/* 进制转换(seqsatck, 测试ok) */
/*
* author: Qian Jipeng
* date: 2019-3-23
* satus: done
*/
#include <stdio.h>
#include <stdlib.h>
#define maxsize 10
typedef struct
{
int data[maxsize];
int top;
}seqstack, *pseqstack;
pseqstack init_stack(){
pseqstack s = (pseqstack)malloc(sizeof(seqstack));
if(s){
s -> top = -1;
}
return s;
}
void push_stack(pseqstack s, int e){
if (!s || s -> top > maxsize -1){
printf("入栈失败!\n");
//return 0;
}
else{
s -> top ++; /*一定要先把TOP加一,否则top 原来是-1,导致第一个元素入栈失败(bug fixed!) */
s -> data[s -> top] = e;
//return 1;
}
}
int pop_stack(pseqstack s, int *x){
if (!s || s -> top == -1){
printf("出栈失败!\n");
return -1;
}
else{
*x = s -> data[s -> top];
s -> top --;
return *x;
}
}
/* 输出栈的每一个元素 */
void print_each(pseqstack s){
int top0 = s->top;
while(top0 != -1){
printf("%d\n", s->data[top0]);
top0 --;
}
}
/*进制转换,x是十进制de 数,y 是待转换进制*/
void transfer(pseqstack s, int x, int y){
int res;
/* 整除后不等于0, 执行循环 */
while(x != 0){
push_stack(s, (x%y));
x = x / y;
}
//printf("%d\n", s->top);
/* 加上输出功能 */
while(s-> top != -1){
pop_stack(s, &res);
printf("%d", res);
if (s->top == -1){
printf("\n");
}
}
}
int main(){
int num; // 十进制数
int scale; // 要转换的进制数
printf("输入十进制数字,进制数: ");
scanf("%d %d", &num, &scale);
pseqstack S = init_stack();
transfer(S, num, scale);
//print_each(S);
}