源代码:
#include <stdio.h>
#include <stdlib.h>
//程序目的:利用栈进行进制转换
typedef struct {
int data[20];
int top;
} Stack;
void Init(Stack *p) {
p->top = 0;
return;
}
int not_empty(Stack *p) {
return p->top;
}
int Push(Stack *p, int a) {
if (p->top == 10)
return 0;
else {
p->data[p->top] = a;
p->top++;
return 1;
}
}
int Pop(Stack *p, int *a) {
if (p->data == 0)
return 0;
else {
p->top--;
*a = p->data[p->top];
return 1;
}
}
int Top(Stack *p, int *a) {
if (p->data == 0)
return 0;
else {
*a = p->data[p->top-1];
return 1;
}
}
void Conversion (int N, int r) {
Stack s;
int x;
Init(&s);
while (N) {
Push (&s, N%r);
N = N/r;
}
while (not_empty(&s)) {
Pop (&s, &x);
printf("%d ", x);
}
}
int main() {
int N,r;
while(scanf("%d%d", &N, &r) == 2) {
Conversion (N, r);
printf("\n");
}
return 0;
}
运行结果: