gpt4 book ai didi

c - 编写锯齿形矩阵的程序

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

最近,我遇到了一个问题,要求我编写一个动态代码,以 zigzag 模式打印 n x n 矩阵。请帮助我编写代码以获得下面所述的输出。

输出:

rows: 5
cols: 5

1 2 3 4 5

10 9 8 7 6

11 12 13 14 15

20 19 18 17 16

21 22 23 24 25

到目前为止我尝试过的代码是静态的:

#include <stdio.h>

int main(){

int arr[3][3]={1,2,3,
4,5,6,
7,8,9};

int i, j, k;

for(i=0; i<3; i++){
printf("%d",arr[0][i]);
}
printf("\n");
for(j=2; j>=0; j--){
printf("%d",arr[1][j]);
}
printf("\n");
for(k=0; k<3; k++){
printf("%d",arr[2][k]);
}
printf("\n");
return 0;

}

现在我希望用户指定数组的行和列来完成同样的事情..

最佳答案

这应该适合你:

#include <stdio.h>

int main() {

int rows, columns;
int rowCount, columnCount, count = 0;

printf("Please enter rows and columns:\n>");
scanf("%d %d", &rows, &columns);


for(rowCount = 0; rowCount < rows; rowCount++) {

for(columnCount = 1; columnCount <= columns; columnCount++) {

if(count % 2 == 0)
printf("%4d " , (columnCount+(rowCount*columns)));
else
printf("%4d " , ((rowCount+1)*columns)-columnCount+1);

}
count++;
printf("\n");
}


return 0;

}

输入:

5 5

输出:

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

关于c - 编写锯齿形矩阵的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093051/

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