利用栈(以顺序栈作存储结构)实现进制转换。给定一个十进制整数,编程将该数以八进制形式输出。
时间: 2023-10-29 22:12:39 浏览: 41
好的,这个问题我可以回答。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef int Status;
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stackSize;
}SqStack;
Status InitStack(SqStack *S){
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base) exit(0);
S->top = S->base;
S->stackSize = STACK_INIT_SIZE;
return 1;
}
Status Push(SqStack *S, SElemType e){
if(S->top - S->base >= S->stackSize){
S->base = (SElemType *)realloc(S->base, (S->stackSize + STACK_INCREMENT) * sizeof(SElemType));
if(!S->base) exit(0);
S->top = S->base + S->stackSize;
S->stackSize += STACK_INCREMENT;
}
*S->top++ = e;
return 1;
}
Status Pop(SqStack *S, SElemType *e){
if(S->top == S->base) return 0;
*e = *--S->top;
return 1;
}
Status ConvertDecimalToOctal(int decimal, SqStack *S){
while(decimal){
Push(S, decimal % 8);
decimal /= 8;
}
if(!S->top) printf("0");
while(S->top != S->base){
printf("%d", *--S->top);
}
return 1;
}
int main(){
int decimal = 0;
SqStack S;
InitStack(&S);
printf("请输入一个十进制整数:\n");
scanf("%d", &decimal);
printf("转换结果为:");
ConvertDecimalToOctal(decimal, &S);
printf("\n");
return 0;
}
```
输入一个十进制整数,程序将其转换为八进制并输出。