Pavel's answer 展示了如何执行递归。但是,仅采用两个参数(循环数和最大值)的函数没有足够的上下文来实际打印您的示例中的数字。为此,您必须跟踪一些额外的信息。一种方法如下:
void _print_loop(int *values, int width, int cur_col, int max) {
if (cur_col == width) {
for (int i = 0; i < width; i++) {
printf("%d%c", values[i], (i < width - 1) ? ' ' : '\n');
}
} else {
for (int i = 0; i < max; i++) {
values[cur_col] = i;
_print_loop(values, width, cur_col + 1, max);
}
}
}
void print_loop(int width, int max) {
int values[width];
memset(values, 0, width * sizeof(int));
_print_loop(values, width, 0, max);
}
现在print_loop(3, 2) 的行为符合预期。
编辑:实际上,一个可以编写一个有两个参数的函数来做到这一点,通过使用static变量,这些变量在收到一个肯定的@987654325时被初始化@ 争论。在这个初始化阶段之后,函数然后使用负值执行其递归。显然,生成的代码很糟糕,但为了完整起见,我还是会发布它:
void print_loop(int width, int max) {
static int max_width;
static int *values;
if (width > 0) {
max_width = width;
if ((values = calloc(width, sizeof(int))) == NULL) {
perror("calloc");
exit(EXIT_FAILURE);
}
print_loop(-width, max);
free(values);
}
else if (width == 0) {
for (int i = 0; i < max_width; i++) {
printf("%d%c", values[i], (i < max_width - 1) ? ' ' : '\n');
}
}
else {
for (int i = 0; i < max; i++) {
values[-width - 1] = i;
print_loop(width + 1, max);
}
}
}