我在C中完成我的家庭作业时遇到了麻烦。任务给出一个整数n打印所有二进制数字,长度为n,其中没有2个连续的零,包括前导零,请注意至少有一个函数必须是递归的。这是一个例子,如果n是4,那么二进制数10被处理为0010,因此它不会被打印,因为它有2个前导零。我的问题是,如果n = 16,我的代码会崩溃,我不知道为什么即使我做了很多调试。这是我的代码,感谢您的帮助。
void binaries_n_digits_no_00(int n)
{
if(n < 0)
{
return;
}
print_binaries_n_digits_no_00(0,n);
}
void print_binaries_n_digits_no_00(long int current_binary_index,int n)
{
int num_of_leading_zeros;
if((current_binary_index > (power(2,n) - 1)) || n == 0)
{
return;
}
num_of_leading_zeros = n - binary_num_length(current_binary_index);
if((binary_not_contain_00(current_binary_index) == 1) &&
(num_of_leading_zeros == 1 || num_of_leading_zeros == 0)){
if(current_binary_index == 0 && n == 1)
{
printf("\n0");
}
else if(num_of_leading_zeros == 1)
{
if(current_binary_index != 0)
{
printf("\n0");
print_binary(current_binary_index);
}
}
else{
printf("\n");
print_binary(current_binary_index);
}
}
print_binaries_n_digits_no_00(current_binary_index+1,n);
}
int binary_not_contain_00(long int num)
{
if(num/2 == 0)
{
return 1;
}
if(((num%2) == 0) && (((num/2) % 2) == 0))
{
return 0;
}
return binary_not_contain_00(num/2);
}
void print_binary(long int num)
{
if(num > 1)
{
print_binary(num/2);
}
printf("%d",num%2);
}
int binary_num_length(long int num)
{
if(num <= 1)
{
return 1;
}
else{
return (1 + binary_num_length(num/2));
}
}
long int power(int m, int n)
{
if(n == 0)
{
return 1;
}
return m * power(m,n-1);
}