我必须在没有SetCommMask
或for
的情况下编写一个recurcive函数
将所有二进制数从0打印到给定的整数:
e.g。如果整数是while
输出是这样的:
(000)
(001)
(010)
(011)
(100)
(101)
(110)
(111)
这是我尝试过的代码:
7
答案 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);
}