你的代码一团糟;)
说真的:用代码解决任务的第一条规则是编写干净的代码,使用合理的变量命名等。
对于像这样的任务,我建议使用这个。
现在到您的示例代码:它不会编译并且很难阅读您正在尝试做的事情。格式化并带有一些注释:
#include <stdio.h>
#define N 10
int main(void)
{
int mas[N] = {0};
int kst, m, n1, z, a, b;
/* Read width ? */
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d", &kst);
/* Read number of bit's set? */
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d", &n1);
/* m1 is not defined, thus the loop give no meaning.
* Guess you are trying to set "bits" integers to 1.
*/
for (m = 0; m1; m++)
mas[m] = 1;
/* This should be in a function as 1. You do it more then once, and
* 2. It makes the code much cleaner and easy to maintain.
*/
for (m = 0; m < kst; m++)
printf("%d", mas[m]);
printf("\n");
for (m = 0; m < n1; m++) {
for (z = 0; z < (kst - 1); z++) {
if ((mas[z] == 1) && (mas[z + 1] == 0)) {
a = mas[z]; /* Same as a = 1; */
mas[z] = mas[z + 1]; /* Same as mas[z] = 0; */
mas[z + 1] = a; /* Same as mas[z + 1] = 1; */
/* Put this into a function. */
for (b = 0; b < kst; b++)
printf("%d", mas[b]);
printf("\n");
}
}
}
return 0;
}
printf
当一个人不确定发生了什么时,广泛使用是一种宝贵的工具。这不是一个解决方案,(它基本上和你的帖子一样,但是分开了),而是一个可能更容易使用的示例。我还使用 char 数组作为 C 字符串而不是整数数组。在这种情况下更容易使用。
如果您想使用整数数组,我建议您添加一个print_perm(int *perm, int width)
辅助函数以将其从主代码中取出。
#include <stdio.h>
#define MAX_WIDTH 10
int get_spec(int *width, int *bits)
{
fprintf(stderr, "Enter width (max %-2d): ", MAX_WIDTH);
scanf("%d", width);
if (*width > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *width, MAX_WIDTH);
return 1;
}
fprintf(stderr, "Enter set bits (max %-2d): ", *width);
scanf("%d", bits);
if (*bits > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *bits, MAX_WIDTH);
return 1;
}
return 0;
}
void permutate(int width, int bits)
{
char perm[MAX_WIDTH + 1];
int i, j;
/* Set "bits" */
for (i = 0; i < width; ++i)
perm[i] = i < bits ? '1' : '0';
/* Terminate C string */
perm[i] = '\0';
fprintf(stderr, "\nPermutations:\n");
printf("%s\n", perm);
for (i = 0; i < bits; ++i) {
/* Debug print current perm and outer iteration number */
printf("%*s LOOP(%d) %s\n",
width, "", i, perm
);
for (j = 0; j < (width - 1); ++j) {
if (perm[j] == '1' && perm[j + 1] == '0') {
perm[j] = '0';
perm[j + 1] = '1';
printf("%s j=%d print\n",
perm, j
);
} else {
/* Debug print */
printf("%*s j=%d skip %s\n",
width, "", j, perm
);
}
}
}
}
int main(void)
{
int width, bits;
if (get_spec(&width, &bits))
return 1;
permutate(width, bits);
return 0;
}