简体   繁体   English

使用递归函数将十进制转换为二进制

[英]decimal to binary conversion using recursive functions

I have an assignment to convert a number from decimal to binary.我有一个任务将数字从十进制转换为二进制。 My problem is that I need to have it printed out directly from the function, instead of returning it back to main.我的问题是我需要直接从函数中打印出来,而不是将它返回给 main。 Due to this, my printed out code is in the wrong order.因此,我打印的代码顺序错误。 (ex: for 6, my code prints out 011 instead of 110 ) (例如:对于 6,我的代码打印出011而不是110

This is what I have been using for the function:这是我一直用于该功能的内容:

int printBinary(int integer) {
    int remainder;

    if (integer < 1) {
        return 0;
    } else {
        remainder = integer % 2;
        printf("%d", remainder);
        integer = integer / 2;
        printBinary(integer);
        return 0;
    }
}

Does anyone have a suggestion on how I can print it out in reverse, or a different approach entirely?有没有人对我如何反向打印它或完全不同的方法有什么建议?

You should just print the digit after the recursive call that prints the higher order bits.您应该在打印高阶位的递归调用之后打印数字。

Note also that your function prints nothing for 0 , which is probably incorrect.另请注意,您的函数不会为0打印任何内容,这可能是不正确的。

Here is a simplified version:这是一个简化版本:

int printBinary(int integer) {
    if (integer > 1)
        printBinary(integer / 2);
    printf("%d", integer % 2);
    return 0;
}

Your function prints binary digits starting from the tail.您的函数从尾部开始打印二进制数字。 Just change the order of recursive call and printf.只需更改递归调用和 printf 的顺序即可。

int printBinary(int integer)  {

    int remainder;
    if (integer < 1)  {
    return 0;
    }
    else  {
        printBinary(integer / 2);
        remainder = integer % 2;
        printf("%d", remainder);
    return 0;
    }
}

It was它是

printBinary(6);
printf("%d", 0);
printBinary(3);
printf("%d", 1);
printBinary(1);
printf("%d", 1);
printBinary(0);

It is now就是现在

printBinary(6);
printBinary(3);
printBinary(1);
printBinary(0);
printf("%d", 1);
printf("%d", 1);
printf("%d", 0);

Also you could try something like this你也可以尝试这样的事情

#include <stdio.h>
#include <limits.h>

void printBinary(int num) {
  int i;

  // findind the first non 0 binary position from MSB
  for (i = sizeof(int) * CHAR_BIT - 1; i >= 0 && (num & (1 << i)) == 0; i--);

  for (; i >= 0; i--) // start the printing from here, so trailing 0's avoided
    if ((num & (1 << i)) == 0)
      printf("0");
    else
      printf("1");
}

int main() 
{
    printBinary(6);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM