我有两个4x4多维数组,行和列分别标记为A
,B
,C
和D
。当用户输入坐标时,所选的known_location_info的值将更改为bomb_location_info的值。因此,例如,如果输入了AA
,则[1][1]
上的known_location_info
的值将变为[1][1]
上的bomb_location_info
的值。目前,无论输入什么坐标,我都只会更改第一个元素。我的循环中有什么错误?
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];
}
答案 0 :(得分:0)
使用从用户扫描的字符的访问矩阵不是一个好主意。因为每个字符都由ASCII码表示。因此,您将具有字母的ascii值的隐式偏移量(例如ASCII fo A =64。另一方面,矩阵就像数组。它们的索引从0开始。您可以在开始循环之前重新去除ascii偏移量。
答案 1 :(得分:0)
#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];
}