gpt4 book ai didi

c - 用 C 语言编程生成此模式

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

这是我尝试过的代码,它只是生成数字并打印。我完全不知道如何访问行号并交换矩阵行的打印位置。

#include <stdio.h>

int main(void)
{
int i,a[10][10],j,n,count=1;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=count;
printf("%d\t",count++);
}
printf("\n");
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d*\t",a[i][j]);
printf("\n");
}
return 0;
}

我提供了要打印的图案的链接,请检查。

https://drive.google.com/open?id=1DKwW8dQggzNjjtAxwPTEI3nRS9AmpK-2Zw

最佳答案

我的方法是完全避免矩阵:

#include <stdio.h>

int main() {

int number;

(void) scanf("%d", &number);

int twice = 2 * number;
int squared = number * number;

for (int row = 0, upward = number, downward = 2 * squared; row < number; row++) {
int n = ((upward > squared) ? downward : upward) - number + 1;

for (int column = 0; column < number; column++) {
printf("%d*\t", n++);
}

printf("\n");

upward += twice;
downward -= twice;
}

return 0;
}

示例

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

关于c - 用 C 语言编程生成此模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39965829/

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