简体   繁体   English

尝试使用c中的递归将十进制转换为二进制转换器

[英]trying to make decimal to binary converter using recursion in c

and i need to make a decimal to binery converter in c with recursion but the output is wrong ex decimal = 22, correct binary = 10110, output = 01101我需要用递归在 c 中制作一个十进制到二进制转换器,但输出是错误的,例如十进制 = 22,正确的二进制 = 10110,输出 = 01101

so this is the code that i came up with所以这是我想出的代码

#include <stdio.h>

int biner (int a){


    if (a == 1)
    return 1;

    else if (a % 2 == 1)
    {
    printf ("1");
    return biner (a / 2);
    }


    else
    {
    printf ("0");
    return biner (a / 2);
    }



}


int main () {
    int a;
    printf ("Masukan angka ");
    scanf ("%d", &a);


    printf ("%d", biner (a));



}

which part do i need to change thanks in advance我需要更改哪一部分提前谢谢

OP's code output is in the wrong order as it needs to recurse before printing to print the most significant digits first. OP 的代码输出顺序错误,因为它需要在打印之前递归以首先打印最高有效数字。

Instead of代替

printf ("1");   // prints least significant digit
biner (a / 2);  // prints most significant digits

More like更像

biner (a / 2);  // prints most significant digits
printf ("1");   // prints least significant digit

There really is no need to return a value, let biner() can do all printing.真的不需要返回值,让biner()可以完成所有打印。

As code is not attempting to print a sign , might as well use unsigned a .由于代码没有尝试打印符号,不妨使用unsigned a

OP's code recurses endlessly if a == 0 .如果a == 0 OP 的代码会无限递归。 Only recurse if a >= 1 .仅在a >= 1递归。 ( a binary digit exist to the left.) (左边有一个二进制数字。)

With d as 0 or 1, The binary digit to print can use putchar('0' + d) d为 0 或 1,要打印的二进制数字可以使用putchar('0' + d)

Suggested simplification:建议简化:

#include <stdio.h>

void biner(unsigned a) {
  if (a > 1) {   // Do binary digits exist to the left?
    biner(a/2);  // Print them.
  }
  putchar('0' + a%2);  // Now print the least significant digit.
}

int main(void) {
  unsigned a;
  printf("Masukan angka ");
  scanf("%u", &a);

  biner(a);
  putchar('\n');
}

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

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