C语言 实现栈 进制转换

C语言 实现栈 进制转换

10进制转换2进制 demo

在C语言中,你可以使用栈(stack)数据结构来实现进制转换。以下是一个简单的C语言程序,使用栈来实现不同进制数的转换:

1、定义栈结构及基本pop & push 操作

C语言 实现栈 进制转换

栈的基本操作

#include <stdio.h>
#include <stdlib.h>

// 定义一个结构体表明栈
struct Stack {
    int *data;
    int top;
    int size;
};

// 初始化栈
void initStack(struct Stack *stack) {
    stack->data = (int *)malloc(100 * sizeof(int));
    stack->top = -1;
    stack->size = 100;
}

// 检查栈是否为空
int isEmpty(struct Stack *stack) {
    return stack->top == -1;
}

// 检查栈是否已满
int isFull(struct Stack *stack) {
    return stack->top == stack->size - 1;
}

// 入栈操作
void push(struct Stack *stack, int value) {
    if (isFull(stack)) {
        printf("栈已满,无法入栈。
");
    } else {
        stack->top++;
        stack->data[stack->top] = value;
    }
}

// 出栈操作
int pop(struct Stack *stack) {
    if (isEmpty(stack)) {
        printf("栈为空,无法出栈。
");
        return -1;
    } else {
        int topValue = stack->data[stack->top];
        stack->top--;
        return topValue;
    }
}

// 打印栈顶元素
int top(struct Stack *stack) {
    if (!isEmpty(stack)) {
        return stack->data[stack->top];
    }
    printf("栈为空,无栈顶元素。
");
    return -1;
}

C语言 实现栈 进制转换

push operation

2、不同进制转换

C语言 实现栈 进制转换

transfer

// 十进制转二进制
void decToBinary(struct Stack *stack, int num) {
    while (num != 0) {
        push(stack, num % 2);
        num /= 2;
    }
}

// 二进制转十进制
int binaryToDec(struct Stack *stack) {
    int result = 0;
    while (!isEmpty(stack)) {
        int popValue = pop(stack);
        result += popValue * (int)pow(2, stack->top);
    }
    return result;
}

3、main 主函数测试

C语言 实现栈 进制转换

coding the world

int main() {
    struct Stack stack;

    // 初始化栈
    initStack(&stack);

    int num, result;

    printf("请输入一个十进制数:");
    scanf("%d", &num);

    // 十进制转二进制
    decToBinary(&stack, num);
    printf("十进制数 %d 转换为二进制为:", num);
    while (!isEmpty(&stack)) {
        printf("%d", top(&stack));
    }
    printf("
");

    // 二进制转十进制
    result = binaryToDec(&stack);
    printf("二进制数转换为十进制为:%d
", result);

    return 0;
}

4、代码说明-readme

C语言 实现栈 进制转换

read me

在上述示例中,我们定义了一个栈结构 Stack,包含数据指针、栈顶指针和栈的大小。

我们实现了栈的基本操作:初始化栈、检查栈是否为空、检查栈是否已满、入栈、出栈、打印栈顶元素。

然后,我们实现了十进制转二进制和二进制转十进制的功能函数。

在 main 函数中,我们第一初始化栈,然后通过 scanf 输入一个十进制数。调用 decToBinary 函数将十进制数转换为二进制,并将二进制数入栈。接着,我们通过循环出栈并打印二进制数的每一位。

最后,调用 binaryToDec 函数将栈中的二进制数转换为十进制,并打印结果。

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...