利用栈实现将十进制的数转换为任意进制的数,使用c语言
时间: 2023-05-31 22:05:56 浏览: 110
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
void convert(int num, int base) {
Stack s;
initStack(&s);
while (num > 0) {
push(&s, num % base);
num /= base;
}
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
}
int main() {
int num, base;
printf("Enter a decimal number: ");
scanf("%d", &num);
printf("Enter a base: ");
scanf("%d", &base);
printf("The number in base %d is: ", base);
convert(num, base);
printf("\n");
return 0;
}
```
阅读全文