我正在尝试将我的数独解决程序的结果打印到终端中,如下所示:
+-------+-------+-------+
| 1 2 3 | 4 5 6 | 7 8 9 |
| 1 2 3 | 4 5 6 | 7 8 9 |
| 1 2 3 | 4 5 6 | 7 8 9 |
+-------+-------+-------+
| 1 2 3 | 4 5 6 | 7 8 9 |
| 1 2 3 | 4 5 6 | 7 8 9 |
| 1 2 3 | 4 5 6 | 7 8 9 |
+-------+-------+-------+
| 1 2 3 | 4 5 6 | 7 8 9 |
| 1 2 3 | 4 5 6 | 7 8 9 |
| 1 2 3 | 4 5 6 | 7 8 9 |
+-------+-------+-------+
我将我的解决方案存储在一维数组中,但找不到打印它的方法。到目前为止,这是我想出的:
printf("| %c %c %c | %c %c %c | %c %c %c |\n", test[0],test[1],test[2],test[3],test[4],test[5],test[6],test[7],test[8]);
我不能使用任何循环,因为我需要在数字周围画“墙”。有没有更好的方法呢?为什么
char test[] = {'1','2','3','4','5','6','7','8','9'};
int i = 0;
printf("| %c %c %c | %c %c %c | %c %c %c |\n", test[i++],test[i++],test[i++],test[i++],test[i++],test[i++],test[i++],test[i++],test[i++]);
返回| 9 8 7 | 6 5 4 | 3 2 1 |
谢谢。
最佳答案
这是将其分解为(嵌套)循环的一种方法:
void print_data_row(const char *p) {
printf("|");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf(" %c", p[i*3 + j]);
}
printf(" |");
}
printf("\n");
}
void print_separator(void) {
printf("+-------+-------+-------+\n");
}
...
print_separator();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
print_data_row(&board[(i*3 + j) * 9]);
}
print_separator();
}
关于c - 在 C 中的其他输出之间打印数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32287311/