gpt4 book ai didi

c - 具有多个 header 的循环

转载 作者:行者123 更新时间:2023-11-30 14:50:48 25 4
gpt4 key购买 nike

我经常遇到循环内重复相同代码但需要多个循环的问题。一个简单的例子是沿着正方形的边缘移动。

/*This code moves the variables x and y around the outside of a square counterclockwise starting from the origin.*/
for(y=0,x=0,x<width;x++);
for(,y<width;y++);
for(,x>0;x--);
for(,y>0;y--);

但是,通常您需要重复对方 block 的坐标进行一些操作。这意味着创建 4 个独立的作用域,每个作用域中重复相同的代码。是否有一些代码允许您使用多个顺序循环条件?该代码可能如下所示:

[  for(y=0,x=0,x<width;x++),    for(,y<width;y++),    for(,x>0;x--),    for(,y>0;y--)  ]
{
//Do something over the perimeter of the square E.g. color in a pixel
}

我知道有迭代器,但我认为与连接循环相比,它们很麻烦。是否有任何语言确实具有这样的重复循环结构?

最佳答案

至于你的具体问题 - 没有任何东西可以直接实现据我所知,但是..我在大学里为此问题编写了一些代码,也许你可以使用它作为基础

基本上,您可以从单个迭代器计算坐标 - 这是一个令人讨厌的代码,但也许它会帮助您解决问题

它将打印出 10x10 正方形的正方形坐标(1 个索引)

#define WIDTH 10
int main()
{
int iter = 0;
int x = 0,y = 0;
while ( iter < (WIDTH*4) ) {
if ( iter < WIDTH ) {
x = iter;
y = 0;
} else if ( iter >= WIDTH && iter < ( 2 * WIDTH ) ) {
x = WIDTH -1;
y = (iter % WIDTH) ;
} else if ( iter >= (2 * WIDTH) && iter < ( 3 * WIDTH ) ) {
x = (WIDTH) - (iter - (2 * WIDTH)) - 1;
y = WIDTH - 1;
} else {
x = 0;
y = (4 * WIDTH) - iter - 1;
}
printf("(%d, %d) ", x+1 ,y+1 );
iter++;
}
printf("\n");

return 0;
}

注意:角坐标重复

关于c - 具有多个 header 的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48779644/

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