gpt4 book ai didi

c++ - 递归似乎仅在某种程度上起作用-如何调试此类问题?

转载 作者:行者123 更新时间:2023-12-01 14:43:54 24 4
gpt4 key购买 nike

我目前正在编写程序,使用递归方法绘制Sierpinski地毯。我的程序代码如下:

#include <iostream>
#include <stdio.h>

const int L = 4;
const int N = 81;
unsigned char output[N][N][3];

void prepareBoard()
{
for (size_t y = 0; y < N; y++)
{
for (size_t x = 0; x < N; x++)
{
output[y][x][0] = 0;
output[y][x][1] = 0;
output[y][x][2] = 0;
}
}
}

void drawRed(int x, int y)
{
output[x][y][0] = 255;
output[x][y][1] = 0;
output[x][y][2] = 0;
}

void drawCarpet(int y, int x, int length, int l)
{
if (l < L)
{
int x1, x2;
int part = length / 3;
for (size_t i = 0; i < length; i++)
{
for (size_t j = 0; j < length; j++)
{
if (i > part && i < part * 2 && j > part && j < part * 2)
{
drawRed(i+x, j+y);
}
}
x1 = x + part;
x2 = x + part * 2;
drawCarpet(x, x, part, l + 1); // 0 0
drawCarpet(x1, x, part, l + 1); // 9 0
drawCarpet(x2, x, part, l + 1); // 17 0
drawCarpet(x, x1, part, l + 1); // 0 9
drawCarpet(x2, x1, part, l + 1); // 0 17
drawCarpet(x, x2, part, l + 1); // 9 17
drawCarpet(x1, x2, part, l + 1); //
drawCarpet(x2, x2, part, l + 1); //
}
}
}

int main()
{
FILE *fp;
fp = fopen("output.ppm", "wb");
fprintf(fp, "P6\n %s\n %d\n %d\n %d\n", "# ", N, N, 255);

prepareBoard();
drawCarpet(0, 0, N, 0);

for (size_t y = 0; y < N; y++)
{
for (size_t x = 0; x < N; x++)
{
fwrite(output[y][x], 1, 3, fp);
}
}

fclose(fp);
return 0;
}

我如何启动该功能:
drawCarpet(0, 0, 243, 0);

问题是该函数可以正常工作到第二个深度-然后它仅在两个“子正方形”上开始工作。这是程序的输出。 outputimg

我欢迎任何建议,尤其是在解决此类问题的方法上。我在中间找到像素的算法也不尽人意,我也很乐意就此提出一些建议。

最佳答案

还没有测试过,但我相信问题在于递归调用中-您不使用y

        x1 = x + part;
x2 = x + part * 2;
drawCarpet(x, x, part, l + 1); // why no dependency on y?
drawCarpet(x1, x, part, l + 1);
drawCarpet(x2, x, part, l + 1);
drawCarpet(x, x1, part, l + 1);
drawCarpet(x2, x1, part, l + 1);
drawCarpet(x, x2, part, l + 1);
drawCarpet(x1, x2, part, l + 1);
drawCarpet(x2, x2, part, l + 1);

应该是这样的:
        x1 = x + part;
x2 = x + part * 2;
y1 = y + part;
y2 = y + part*2;
drawCarpet(x, y, part, l + 1);
drawCarpet(x1, y, part, l + 1);
drawCarpet(x2, y, part, l + 1);
drawCarpet(x, y1, part, l + 1);
drawCarpet(x2, y1, part, l + 1);
drawCarpet(x, y2, part, l + 1);
drawCarpet(x1, y2, part, l + 1);
drawCarpet(x2, y2, part, l + 1);

关于c++ - 递归似乎仅在某种程度上起作用-如何调试此类问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com