利用栈实现十进制转八进制C语言含有头文件实现文件
时间: 2024-02-04 11:03:41 浏览: 85
十进制转换为二进制_技术要点-client-side.data.storage.keeping.it.local.14919
好的,下面是十进制转八进制的栈实现过程的 C 语言代码,包含头文件和实现文件:
栈的头文件 stack.h:
```c
#ifndef STACK_H
#define STACK_H
#define MAX_SIZE 100
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;
void push(Stack *s, int num);
int pop(Stack *s);
int is_empty(Stack *s);
#endif
```
栈的实现文件 stack.c:
```c
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
void push(Stack *s, int num) {
if (s->top == MAX_SIZE - 1) {
printf("Stack is full\n");
exit(1);
}
s->data[++s->top] = num;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty\n");
exit(1);
}
return s->data[s->top--];
}
int is_empty(Stack *s) {
return s->top == -1;
}
```
十进制转八进制的实现文件 decimal_to_octal.c:
```c
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *decimal_to_octal(int decimal_num) {
Stack s;
s.top = -1;
while (decimal_num > 0) {
int remainder = decimal_num % 8;
push(&s, remainder);
decimal_num /= 8;
}
char *octal_num = (char *)malloc(sizeof(char) * (s.top + 2));
int index = 0;
while (!is_empty(&s)) {
octal_num[index++] = pop(&s) + '0';
}
octal_num[index] = '\0';
return octal_num;
}
```
主函数文件 main.c:
```c
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char *decimal_to_octal(int decimal_num);
int main() {
int decimal_num = 123;
char *octal_num = decimal_to_octal(decimal_num);
printf("%d in decimal is %s in octal\n", decimal_num, octal_num);
free(octal_num);
return 0;
}
```
你可以将这些文件放在同一个目录下,使用编译器将这些文件编译为可执行文件,运行可执行文件即可得到结果。
阅读全文