【发布时间】:2021-08-24 02:23:48
【问题描述】:
在给定以下参数的情况下,我正在尝试编写一个打印 X 和 O 矩阵的算法:
int numRows
int numCols
int charsPerCol
int charsPerRow
例如打电话
printXOMatrix(int charsPerCol, int charsPerRow, int numCols, int numRows);
带参数
printXOMatrix(3,2,15,8);
将导致以下内容被打印到标准输出:
XXXOOOXXXOOOXXX
XXXOOOXXXOOOXXX
OOOXXXOOOXXXOOO
OOOXXXOOOXXXOOO
XXXOOOXXXOOOXXX
XXXOOOXXXOOOXXX
OOOXXXOOOXXXOOO
OOOXXXOOOXXXOOO
到目前为止,这是我的代码,如果列数/每列的字符数不同,它似乎可以正确打印,但例如在以下情况下会失败:
printXOMatrix(2,2,8,8);
以下内容被打印到标准输出:
XXOOXXOO
OOXXOOXX
OOXXOOXX
XXOOXXOO
XXOOXXOO
OOXXOOXX
OOXXOOXX
XXOOXXOO
如何处理这种极端情况/清理我的代码?这是我目前所拥有的:
#include <stdio.h>
void getXAndOGrid(int charsPerCol, int charsPerRow, int numCols, int numRows) {
char c = 'X';
for (int i=1; i<=(numCols*numRows); i++) {
// if current index is divisible by the columns (new row)
if (i % numCols == 0) {
// print character, then newline
printf("%c\n", c);
// if current index is divisible by number of columns times num of chars in column
if (i % (numCols * charsPerRow) == 0) {
if (c == 'O') {
c = 'X';
} else {
c = 'O';
}
}
// else if current index is divisible by num in row before it alternates
// and is not divisible by number of columns
} else if (i % charsPerCol == 0) {
printf("%c", c);
if (c == 'O') {
c = 'X';
} else {
c = 'O';
}
} else {
printf("%c", c);
}
}
}
int main() {
getXAndOGrid(3,2,15,8);
return 0;
}
【问题讨论】:
-
您已经在最初声明函数的方式和实际实现方式之间交换了顺序或参数。是哪个?
-
@selbie 感谢您告诉我,已修复。