#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/