arrays - 处理非法数组
问题描述
一些上下文:这个程序读取 Stone 的行并将它们放到地图上。
程序应该首先询问 STONE 的行数作为整数。然后,程序会将行的位置扫描为一组四个整数,格式如下:
行列长度值
行和列表示要放置在地图上的水平线块中最左边的块。长度告诉你在这条水平线上应该有多少石头。在此示例中,假设第四个整数始终为 1,表示石头。
示例:命令含义
0 0 5 1 放置一条石头线,从 [0][0] 开始,到 [0][4] 结束。该行中的所有 5 个方格都将设置为 1 (STONE)。
注意:前三个整数(行列长度)可能导致部分或全部在地图之外的行。如果是这种情况,您应该完全忽略此行,不要对地图进行任何更改。
因此问题:当我输入非法数组值时,例如 22 22 22 1,它会简单地停止程序并说出现错误。我如何让程序简单地忽略该命令行并继续其余部分,就好像它从未输入过一样?
#define SIZE 15
#define EMPTY 0
#define STONE 1
void printMap(int map[SIZE][SIZE], int playerX);
int main (void) {
// This line creates our 2D array called "map" and sets all
// of the blocks in the map to EMPTY.
int map[SIZE][SIZE] = {EMPTY};
int playerX = SIZE / 2;
printf("How many lines of stone? ");
int linesOfStone;
scanf("%d", &linesOfStone);
printf("Enter lines of stone:\n");
int rowPos;
int columnPos;
int stoneLength;
int stoneValue;
int i = 0;
while (i < linesOfStone) {
scanf("%d %d %d %d", &rowPos, &columnPos, &stoneLength, &stoneValue);
//ERROR ERROR this is where i attempt to fix tackle the problem but my logic seems lost...
if (rowPos < 0 || columnPos < 0) {
rowPos = 0;
columnPos = 0;
map[0][0] = 0;
} else if (rowPos > SIZE || columnPos > SIZE) {
rowPos = 0;
columnPos = 0;
map[0][0] = 0;
} else {
map[rowPos][columnPos] = stoneValue;
}
int j = 0;
while (j < stoneLength) {
map[rowPos][columnPos + j] = 1;
j++;
}
i++;
}
printMap(map, playerX);
return 0;
}
void printMap(int map[SIZE][SIZE], int playerX) {
// Print values from the map array.
int i = 0;
while (i < SIZE) {
int j = 0;
while (j < SIZE) {
printf("%d ", map[i][j]);
j++;
}
printf("\n");
i++;
}
// Print the player line.
i = 0;
while (i < playerX) {
printf(" ");
i++;
}
printf("P\n");
}
解决方案
减一
rowPos > SIZE
应该rowPos >= SIZE
。对columnPos > SIZE
.
建议进行额外的测试以确保在stoneLength
.
没有范围限制stoneLength
范围限制最佳应用独立性
//if (rowPos < 0 || columnPos < 0) {
if (rowPos < 0) {
推荐阅读
- css - 如何在引导导航栏中创建链接以沿水平方向均匀占用空间?
- swift - 在 ViewController 中使用方法的简单问题
- python - 如何获取与特定键匹配的发电机数据库中的项目
- javascript - 如何使用 jQuery 或 Javascript 将动态 div 内容拆分为具有特定高度的两个 div 内容?
- php - CodeIgniter 会话持有值 1 而不是 true
- php - 光滑的轮播显示不正确
- python - 使用 Excel / Python 从 Excel 中提取信息(通过更新数组)
- docker - Kubernetes - docker 驱动程序上的入口 - minikube 1.16
- c++ - 如何在从不同类的函数调用 std::async 时传递另一个类的函数?
- postgresql - 使用 SQLX、Squirrel 执行 JOIN 的最佳实践