c - 打印此二进制代码...向后。在 C

标签 c binary radix

#include <stdio.h>
#include <math.h>
/* converts to binary */

int main()
{
    unsigned int decimalNUM = 0;
    printf("Enter a number to be converted to binary.\t");
    scanf("%d", &decimalNUM);
    fflush(stdin);
    baseConv(decimalNUM);
    getchar();
    return 0;
}
baseConv(unsigned int n){
if (n == 0) ;
      while (n > 0){
      printf("%d", n%2);
      n = n >> 1;
              }
return 0;
}

我现在知道如何执行此操作,但它向后打印。我将如何扭转它?

最佳答案

如果您想要一种方法来反转这样的操作,一种方法是使用堆栈数据结构。

不是在主循环中打印值,而是将它们压入堆栈。

然后,一旦完成,从堆栈中弹出一个项目并打印它,然后继续这样做直到堆栈为空。堆栈被称为 LIFO 结构(后进先出),是一种方便的存储方式,以便以后按照与生成顺序相反的顺序进行检索。

伪代码:

def baseConv (n):
    create stack s
    while n > 0:
        push n % 2 onto s
        n = n >> 1
    while not empty(s):
        pop n from s
        print n

我还应该补充声明:

if (n == 0);

根本没有做任何有用的事情。

关于c - 打印此二进制代码...向后。在 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4894470/

相关文章:

c - printf和co如何区分float和double

char[] 到 uint64_t

C++ 构造函数、常量、继承和避免重复

c - 如何在运行主函数之前更改其参数

c - 如何在 C 中使用这个定义的类型?

c - C 中使用多个分离线程的内存泄漏

c++ - 将整数插入字符数组

c - 如何确定单个数组中位的重复模式

linux - 使用 bash 添加一个常数来移动文件名

assembly - "fh"后缀对于 Intel 汇编中的 "38fh"这样的数字意味着什么