用栈写出数制转换c语言完整代码及其运行界面
时间: 2024-11-16 07:10:31 浏览: 0
全国计算机等级考试二级C语言上机考试具有三种题型.pdf
数制转换是将一个数从一种数制表示转换为另一种数制表示的过程。下面是使用栈实现十进制转换为任意进制的C语言代码及其运行界面。
```
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef struct {
int *base;
int *top;
int stackSize;
} SqStack;
void InitStack(SqStack *S) {
S->base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
if (!S->base) {
exit(0);
}
S->top = S->base;
S->stackSize = STACK_INIT_SIZE;
}
void Push(SqStack *S, int e) {
if (S->top - S->base >= S->stackSize) {
S->base = (int *)realloc(S->base, (S->stackSize + STACK_INCREMENT) * sizeof(int));
if (!S->base) {
exit(0);
}
S->top = S->base + S->stackSize;
S->stackSize += STACK_INCREMENT;
}
*(S->top) = e;
S->top++;
}
int Pop(SqStack *S) {
int e;
if (S->top == S->base) {
return -1;
}
S->top--;
e = *(S->top);
return e;
}
int StackLen(SqStack S) {
return S.top - S.base;
}
int main() {
SqStack S;
int N, M, num, e;
InitStack(&S);
printf("请输入要转换的十进制数:");
scanf("%d", &num);
printf("请输入要转换的进制数:");
scanf("%d", &M);
N = num;
while (N) {
Push(&S, N % M);
N /= M;
}
printf("转换结果为:");
while (StackLen(S)) {
e = Pop(&S);
if (e < 10) {
printf("%d", e);
} else {
printf("%c", e - 10 + 'A');
}
}
printf("\n");
return 0;
}
```
运行界面:
```
请输入要转换的十进制数:123
请输入要转换的进制数:16
转换结果为:7B
```
阅读全文