我正在编写一个以Z字形图案打印n x n矩阵的动态代码。请帮我解释下面的输出代码:
到目前为止,我在Rizier123的帮助下尝试过的代码是水平曲折模式:
#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
我想要相同的锯齿形图案输出但是垂直..
修改
预期产出:
1 10 11 20 21 30
2 9 12 19 22 29
3 8 13 18 23 28
4 7 14 17 24 27
5 6 15 16 25 26
答案 0 :(得分:5)
这应该适合你:
#include <stdio.h>
int main() {
int rows, columns;
int rowCount, columnCount;
printf("Please enter rows and columns:\n>");
scanf("%d %d", &rows, &columns);
for(rowCount = 0; rowCount < rows; rowCount++) {
for(columnCount = 0; columnCount < columns; columnCount++) {
if(columnCount % 2 == 0)
printf("%4d " , rows*(columnCount)+rowCount+1);
else
printf("%4d " , (rows*(columnCount+1))-rowCount);
}
printf("\n");
}
return 0;
}
输入:
5 5
输出:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25