Как прокомментировал вопрос user3386109, проблема в n = 3*n;
. Это должно быть n = 2*n + 1;
, потому что каждая ячейка состоит из 2 × 2 символов, и вам нужен один дополнительный ряд символов.
Рассмотрим этот контрпример:
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
const wchar_t names[] = L"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static void wide_grid(FILE *out, const int rows, const int cols)
{
int row, col;
/* We can only do single-character cell names. */
if (rows > wcslen(names) || cols > wcslen(names))
return;
/* Top left corner of the grid, including the top edge of that cell. */
fwprintf(out, L"┌──");
/* Top edges of each cell in the topmost row, except the leftmost cell. */
for (col = 2; col <= cols; col++)
fwprintf(out, L"┬──");
/* Top right corner of the grid. */
fwprintf(out, L"┐\n");
/* Cells for the top row, including their left edges. */
for (col = 1; col <= cols; col++)
fwprintf(out, L"│%lc%lc", names[0], names[col-1]);
/* The right edge of the last cell in the top row. */
fwprintf(out, L"│\n");
/* Loop over the rest of the cell rows. */
for (row = 2; row <= rows; row++) {
/* Top edge of the first cell on this row. */
fwprintf(out, L"├──");
/* Top edges of the rest of the cells. */
for (col = 2; col <= cols; col++)
fwprintf(out, L"┼──");
/* Right edge of the grid. */
fwprintf(out, L"┤\n");
/* Cells themselves, including their left edges. */
for (col = 1; col <= cols; col++)
fwprintf(out, L"│%lc%lc", names[row-1], names[col-1]);
/* Right edge of the grid. */
fwprintf(out, L"│\n");
}
/* Bottom left corner of the grid, including the cell bottom. */
fwprintf(out, L"└──");
/* Bottom edges of the rest of the cells. */
for (col = 2; col <= cols; col++)
fwprintf(out, L"┴──");
/* Bottom right corner of the grid. */
fwprintf(out, L"┘\n");
}
int main(int argc, char *argv[])
{
const int max = wcslen(names);
int rows, cols;
char dummy;
if (!setlocale(LC_ALL, ""))
fprintf(stderr, "Warning: Your C library does not support your current locale.\n");
if (fwide(stdout, 1) < 1)
fprintf(stderr, "Warning: Your C library does not support wide character standard output.\n");
if (argc != 3) {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: %s [ help ]\n", argv[0]);
fprintf(stderr, " %s ROWS COLUMNS\n", argv[0]);
fprintf(stderr, "\n");
return EXIT_SUCCESS;
}
if (sscanf(argv[1], " %d %c", &rows, &dummy) != 1 || rows < 1) {
fprintf(stderr, "%s: Invalid number of rows.\n", argv[1]);
return EXIT_FAILURE;
}
if (rows > max) {
fprintf(stderr, "%s: Too many rows. The maximum is %d.\n", argv[1], max);
return EXIT_FAILURE;
}
if (sscanf(argv[2], " %d %c", &cols, &dummy) != 1 || cols < 1) {
fprintf(stderr, "%s: Invalid number of columns.\n", argv[2]);
return EXIT_FAILURE;
}
if (cols > max) {
fprintf(stderr, "%s: Too many columns. The maximum is %d.\n", argv[2], max);
return EXIT_FAILURE;
}
wide_grid(stdout, rows, cols);
return EXIT_SUCCESS;
}
Эта программа использует вывод широких символов, поэтому вы должны иметь возможность использовать любые символы Unicode, которые поддерживает ваш терминальный шрифт. Они из набора Box Drawing. (Некоторым пользователям Windows могут потребоваться специфичные для Microsoft расширения, описанные выше, чтобы получить правильный вывод, но поскольку я не использую Windows, я их опускаю.)
Также необходимо указать количество строк и столбцов в командной строке. Запуск без параметров показывает краткий текст справки.
Каждая ячейка помечена с меткой строки и столбца, взятой из массива names
. Вы можете разрешить использование больших сеток, добавив символы меток в этот массив.
Каждая строка или цикл в wide_grid()
комментируется, чтобы объяснить назначение каждого фрагмента кода.
Вместо одного вложенного цикла и условных случаев в них мы строим сетку по частям:
┌── ┬── .. ┬── ┐
│11 │12 .. │1c │
├── ┼── .. ┼── ┤ ╲
row = 2 .. rows
│r1 │r2 .. │rc │ ╱
: : : :
└── ┴── .. ┴── ┘
Вот что вы увидите, если запустить его с аргументами 5 12:
┌──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┐
│11│12│13│14│15│16│17│18│19│1A│1B│1C│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│21│22│23│24│25│26│27│28│29│2A│2B│2C│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│31│32│33│34│35│36│37│38│39│3A│3B│3C│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│41│42│43│44│45│46│47│48│49│4A│4B│4C│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│51│52│53│54│55│56│57│58│59│5A│5B│5C│
└──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘