任何程序通过递归十进制到二进制

时间:2017-05-14 00:32:50

标签: c recursion binary decimal

enter image description here

我必须在没有SetCommMaskfor的情况下编写一个recurcive函数 将所有二进制数从0打印到给定的整数:

e.g。如果整数是while输出是这样的:

  

(000)
  (001)
  (010)
  (011)
  (100)
  (101)
  (110)
  (111)

这是我尝试过的代码:

7

2 个答案:

答案 0 :(得分:-1)

此示例涵盖您的以下需求:

  • 递归
  • 显示范围内的二进制数
  • 您可以指定要显示的位数
#include <stdio.h>

void print_binary_numbers(int from, int to, int bits);
void print_binary(int n, int bits);

int main (void){
    int n;
    printf("Please enter an integer: ");
    scanf("%d", &n);
    print_binary_numbers(0, n, 8);
    return 0;
}

/**
 * @param bits Controls the number of displayed bits.
 */
void print_binary(int n, int bits) {
    while (--bits >= 0){
        printf("%s", n & (1 << bits) ? "1" : "0");
    }
}

void print_binary_numbers(int from, int to, int bits) {
    print_binary(from, bits);
    printf("\n");
    if (from < to) {
        print_binary_numbers(from + 1, to, bits);
    }
}

答案 1 :(得分:-1)

用C / *编译-O2选项* /

#include <stdio.h>

void print_binary_number(int decimalNo, int width, char arr[]);

int main (void){
    int a;
    char arr[32] = {0};

    printf("\nPlease enter an integer:\n");
    scanf("%d", &a);
    int width = 0;
    for(unsigned c = a; c; c >>= 1)
        ++width;
    print_binary_number(a, width, arr);
    return 0;
}

void print_binary_number(int decimalNo, int width, char arr[]){
    for(int i = width-1; i>=0; --i)
        printf("%d", arr[i]);
    printf("\n");
    if(!decimalNo)
        return ;
    for(int i = 0, carry = 1, c; carry; ++i, carry = c){
        c = arr[i] & carry;
        arr[i] ^= carry;
    }
    print_binary_number(decimalNo-1, width, arr);
}