c语言使用栈实现进制间转换的完整代码
时间: 2023-05-17 19:05:12 浏览: 91
下面是使用栈实现进制间转换的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top];
}
void convert(int n, int base) {
Stack s;
initStack(&s);
while (n > 0) {
push(&s, n % base);
n /= base;
}
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
}
int main() {
int n, base;
printf("Enter a number: ");
scanf("%d", &n);
printf("Enter a base: ");
scanf("%d", &base);
printf("The number %d in base %d is: ", n, base);
convert(n, base);
printf("\n");
return 0;
}
注意:这段代码只能实现将十进制数转换为其他进制数,不能将其他进制数转换为十进制数。
阅读全文