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

时间:2019-05-19 12:48:35

标签: c

将十进制数字转换为二进制数字的过程如下:

将十进制数递归除以2,并注意每次的余数(为0或1)。

  • 当您点击0时,将其余部分反写为答案

例如,将710(base10)转换为其等效的二进制文件:

预期输出:

710 / 2 = 355, remainder 0
355 / 2 = 177, remainder 1
177 / 2 = 88, remainder 1
 88 / 2 = 44, remainder 0
 44 / 2 = 22, remainder 0
 22 / 2 = 11, remainder 0
 11 / 2 = 5, remainder 1
 5 / 2 = 2, remainder 1
 2 / 2 = 1, remainder 0
 1 / 2 = 0, remainder 1

710 (base10) = 1011000110 (base2)

将余数放在一起(以相反的顺序)将得出71010(以10为底)= 1011000110(以base2为底)

编写一个递归程序,将十进制数转换为等效的二进制数。

无效的示例代码:

#include <stdio.h>

/*int convertToBinary() {

};

void printBinary() {

}*/

int main() {
    int base10 = 710;
    int base2;
    int remainder;

do {
    printf("%d / 2 = %d, remainder: %d\n", base10, base2, remainder);
    remainder = base10 % 2;
    base10 = base10 / 2;
    base2 = base10;
} while (base10 > 0);

    return 0;
}

错误的输出:

710 / 2 = 32766, remainder: -333235520
355 / 2 = 355, remainder: 0
177 / 2 = 177, remainder: 1
88 / 2 = 88, remainder: 1
44 / 2 = 44, remainder: 0
22 / 2 = 22, remainder: 0
11 / 2 = 11, remainder: 0
5 / 2 = 5, remainder: 1
2 / 2 = 2, remainder: 1
1 / 2 = 1, remainder: 0
  1. 如何纠正输出?
  2. 如何将这些作为单独的函数编写?
  3. 如何输出显示“ 710(base10)= 1011000110”的行 (base2)”?

2 个答案:

答案 0 :(得分:1)

  1. 这是基本的实现方式:

    int toBinary(int x) {
        // base case
        if(x==0 || x==1)
            return x;
        printf("%d", toBinary(x/2));
        return x%2;
    }
    int main(){
        int num=710;
        printf("%d", toBinary(num));
    }
    
  2. 如果只想打印行:

    void printBinary(int num) {
        printf("%d (base 10) = ", num);
        int lastBit = toBinary(num);
        printf("%d (base 2)", lastBit);
    }
    

旁注:recursive函数是一个自我调用的函数。您的示例是一个基于循环的简单程序,而不是递归程序。

答案 1 :(得分:0)

int main() {
    int base10 = 710;
    int remainder;

    while (base10 > 0)
    {
        printf("%d / 2 = %d, remainder: %d\n", base10, base10 / 2, base10 % 2);
        base10 = base10 / 2;
    }

    return 0;
}