gpt4 book ai didi

c - 如何在c中打印环形输出?

转载 作者:行者123 更新时间:2023-11-30 17:20:12 25 4
gpt4 key购买 nike

我有 C 程序问题来打印环类型输出。
当用户输入数字5时,程序输出如下:

1     2      3     4    5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

我使用以下逻辑,但我真的失败了,我不知道。

 int main()
{
int a[50],i,j=0,n,k;
printf("Enter the number=");
scanf("%d",&n);

for(i=1;i<=n;i++)
{

if(i>n)
{
j=j+5;
}
else if(i>((2*n)-1))
{
j--;
}
else if(i>((3*n)-2))
{
j=j-5;
}
else if(i>(4*n-4))
{
j++;
}
}
}


很抱歉询问整个程序逻辑,但是,我真的不知道,请帮助我......

最佳答案

这就是您要找的内容

#include <stdio.h>

#define max 25

int main()
{
int spiral[max][max] = {{0}}; // initializing array with 0
int r, c, i = 0, j = -1, count = 1;

printf("\nEnter the row and column for spiral matrix:\n");
scanf("%d%d", &r, &c);

while (count <= r * c) // this loop executes till all the blocks of
{
// array r*c are filled with 0
while (j < c - 1) // Filling the location from left to right
{
// with value of variable count
if(spiral[i][j+1]!=0) // Here we are checking if that location
break; // is already occupied
spiral[i][++j] = count++;
}

while (i < r - 1) // Filling the location from top to bottom
{
if (spiral[i+1][j] != 0)
break;
spiral[++i][j] = count++;
}

while (j > 0) // Filling the location from right to left
{
if(spiral[i][j-1] != 0)
break;
spiral[i][--j] = count++;
}

while (i > 0) // Filling the column from bottom to top
{
if (spiral[i-1][j] != 0)
break;
spiral[--i][j] = count++;
}
}

for (i = 0 ; i < r ; i++)
{
for (j = 0 ; j < c ; j++)
{
printf("%3d",spiral[i][j]); // print the matrix
}
printf("\n");
}
return 0;
}

引用号是here from more details

关于c - 如何在c中打印环形输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659300/

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