【问题标题】:How to access elements of a Matrix using loops如何使用循环访问矩阵的元素
【发布时间】:2019-05-05 17:04:00
【问题描述】:

我有两个 4x4 多维数组,行和列分别标记为ABCD。当用户输入坐标时,选择的 known_location_info 的值被更改为 bomb_location_info 的值。例如,如果输入了AA,则known_location_info 上的[1][1] 值将更改为bomb_location_info[1][1] 的值。目前,无论输入什么坐标,我都只会改变第一个元素。我的循环中有什么不正确的地方?

char inputRow;
char inputColumn;
char letterA = 'A';

void display(int known_location_info[][DIM], int size) {

    printf("  A  B  C  D\n");

    for (int row = 0; row < DIM; row++) {

        printf("%c", letterA);
        letterA++;

        for (int column = 0; column < DIM; column++) {
            printf("%d ", known_location_info[row][column]);
        }
        printf("\n");
    }

    printf("Please select a row and column: ");
    scanf("%c, %c", &inputRow, &inputColumn);
}

void update_known_info(int row, int col, int bomb_location_info[][DIM], 
                       int known_location_info[][DIM]) {

    for (inputRow = letterA; inputRow < DIM; inputRow++) {
        for (inputColumn = letterA; inputColumn < DIM; inputColumn++) {
            row++;
            col++;
        }
    }

    known_location_info[row][col] = bomb_location_info[row][col];
}

【问题讨论】:

  • 你检查过inputRowinputColumn的值吗?

标签: c loops matrix


【解决方案1】:
#include <stdio.h>
#include <assert.h>

#define DIM 4

void display(int known_location_info[][DIM]) {

    printf("  A  B  C  D\n");

    for (int row = 0; row < DIM; ++row) {
        printf("%c ", 'A' + row);
        for (int column = 0; column < DIM; ++column)
            printf("%2d ", known_location_info[row][column]);
        putchar('\n');
    }

    printf("Please select a row and column: ");
    char inputRow; char inputColumn;
    if (scanf(" %c, %c", &inputRow, &inputColumn) != 2 ||
        inputRow < 'A' || 'A' + DIM < inputRow ||
        inputColumn < 'A' || 'A' + DIM < inputRow)
    {
        // handle input error
    }
}

void update_known_info(char row, char col, int bomb_location_info[][DIM],
                       int known_location_info[][DIM])
{
    row -= 'A';
    col -= 'A';

    assert(0 <= row && row < DIM && 0 <= col && col < DIM);

    known_location_info[row][col] = bomb_location_info[row][col];
}

【讨论】:

    【解决方案2】:

    使用从用户扫描的字符访问矩阵不是一个好主意。因为每个字符都由一个 ASCII 码表示。因此,您将拥有字母的 ascii 值的隐式偏移量(例如 ASCII fo A = 64。另一方面,矩阵就像数组。它们从 0 开始索引。您可以在开始循环之前检索 ascii 偏移量。 .

    【讨论】:

      猜你喜欢
      • 2018-10-14
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      相关资源
      最近更新 更多