二进制数转换为十进制数c语言程序代码,数据结构c语言版怎么实现十进制数转换成二进制数(要求用栈)...

这是比较简单的一个小程序,使用了自定义的链表堆栈。考虑到程序不会长期执行,程序在退出时操作系统会自动清理这个程序的私有虚拟内存空间,所以就没有设计清理功能(尽管也很简单)。下面是程序截图:

下面就是程序代码,已经加入了简单的注释信息。

希望可以帮到你!

----------------------------------binary_convert。c----------------------------------

// 为了使用printf()、scanf()和perror()函数

#include

// 为了使用malloc()、free()和exit()函数

#include

typedef struct node *frame;

// 栈帧的数据结构

struct node {

? ?int data;

? ?frame prev;

};

// 堆栈长度

static int len = 0;

// 堆栈的顶部

static frame top = NULL;

// 获得堆栈的栈帧数量(长度)

static int getlen(void) {

? ?return len;

}

// 判断堆栈是否为空

static int is_empty(void) {

? ?return (0 == len);

}

// 产生一个新的栈帧

static frame new_frame(int data) {

? ?frame nf = (frame) malloc(sizeof(struct node));

? ?// 下面3句是在没有分配到动态内存时做的错误处理

? ?if (NULL == nf) {

? ? ? ?perror("Error: can not allocate memory, quit。

");

? ? ? ?exit(0);

? ?}

? ?nf->data = data;

? ?nf->prev = NULL;

? ?return nf;

}

// 出栈操作

static int pop(void) {

? ?if (!is_empty()) {

? ? ? ?int ret_int = top->data;

? ? ? ?frame out = top;

? ? ? ?top = top->prev;

? ? ? ?len--;

? ? ? ?free(out);

? ? ? ?return ret_int;

? ?} else {

? ? ? ?perror("Error: can not pop from stack, because the stack is empty。

");

? ? ? ?exit(0);

? ?}

}

// 入栈操作

static void push(int data) {

? ?frame in = new_frame(data);

? ?in->prev = top;

? ?top = in;

? ?len ;

}

// 将十进制数字的余数存储到堆栈之中

void binary_convert(int num) {

? ?while(num / 2) {

? ? ? ?push(num % 2);

? ? ? ?num /= 2;

? ?}

? ?push(num % 2);

}

// 利用堆栈打印二进制数字

void print_binary(void) {

? ?while(!is_empty())

? ? ? ?printf("%d", pop());

}

int main(void) {

? ?// 用于接收用户输入的十进制数字

? ?int user_in = 0;

? ?printf("Please input a positive decimal integer: ");

? ?scanf("%d", &user_in);

? ?// 将十进制数字通过堆栈转换为二进制数字

? ?binary_convert(user_in);

? ?printf("Binary number: ");

? ?// 打印二进制数字

? ?print_binary();

? ?printf("

");

? ?return 0;

}。

全部

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值