我一直在为Game of Life开发一个程序,我认为即将到来,但是我唯一的挫折是程序错误地读取了邻居的数量,因此输出是因此不正确。
#include <stdio.h>
#include <stdbool.h>
int numRows;
int numColumns;
int steps;
void printGrid(char grid[numRows][numColumns]) {
int i, j;
for(i=0; i<numRows; i++) {
for(j=0;j<numColumns;j++) {
printf("%c", grid[i][j]);
if (j == numRows - 1) {
printf("\n");
}
}
}printf("\n");
}
int neighbourValue(int row, int column, char grid[row][column]) {
if(row < 0 ||
row > numRows -1 ||
column < 0 ||
column > numColumns -1 ||
grid[row][column] == '.') {
return 0;
} else {
return 1;
}
}
int getNeighbourCount(int row, int column, char grid[row][column]) {
int neighbour = 0;
neighbour += neighbourValue(row-1, column-1, grid); // Above Left
neighbour += neighbourValue(row-1, column, grid); // Above
neighbour += neighbourValue(row-1, column+1, grid); // Above Right
neighbour += neighbourValue(row, column-1, grid); // Left
neighbour += neighbourValue(row, column+1, grid); // Right
neighbour += neighbourValue(row+1, column-1, grid); // Below Right
neighbour += neighbourValue(row+1, column, grid); // Below
neighbour += neighbourValue(row+1, column+1, grid); //Below Left
return neighbour;
}
void calculations(int row, int column, char grid[row][column]) {
char grid2[row][column];
int neighbour, x, y;
for(x = 0; x < numRows; x++) {
for(y = 0; y < numColumns; y++) {
neighbour = getNeighbourCount(x, y, grid);
if(neighbour == 3) {
grid2[x][y] = 'X';
} else if (neighbour == 2 && grid[x][y] == 'X') {
grid2[x][y] = 'X';
} else {
grid2[x][y] = '.';
}
}
} printf("\n %d \n", getNeighbourCount(0,1, grid));
我在这里添加了一个小调试打印语句,打印出上面打印网格的网格上(0,1)的邻居数。
for(x = 0; x < numRows; x++) {
for(y = 0; y < numColumns; y++) {
grid[x][y] = grid2[x][y];
}
}
printGrid(grid);
}
int main() {
int counter = 0;
scanf("%d %d %d", &numRows, &numColumns, &steps); //Setting up the array
char grid[numRows][numColumns];
int i, j;
for(i=0; i<numRows; i++) {
for(j=0;j<numColumns;j++) {
scanf(" %c", &grid[i][j]);
}
}
printGrid(grid);
do{
calculations(numRows, numColumns, grid);
counter++;
}while(counter < steps);
}
我已经包含了整个代码,但我认为问题出现在neighbourValue附近,因为边界可能是错误的。 典型输入为3 3 3(行列步骤) 然后是XXX XXX XXX。 有人能够测试它,看看它出错了吗? 我有一个潜行的怀疑,在0,1的位置(在其他位置,可能是'包装'和阅读网格的另一端的邻居。
答案 0 :(得分:0)
在OP的代码中,grid
被声明为可变长度的2D数组:
int numRows; // global variables
int numColumns;
// ...
scanf("%d %d %d", &numRows, &numColumns, &steps);
char grid[numRows][numColumns];
但其尺寸仅作为参数正确传递给calculation
函数:
void calculations(int row, int column, char grid[row][column])
// this signature ^^ ^^^ ^^^ ^^^^
// is common to almost all of the OP's functions
calculations(numRows, numColumns, grid);
// ^^^^^^^ ^^^^^^ correct parameters, the sizes of the grid
在其他函数的调用中,传递了错误的参数:
// e.g.
int neighbourValue(int row, int column, char grid[row][column])
// ^^^ ^^^^^^ ^^^ ^^^^^^
neighbour += neighbourValue(row-1, column-1, grid); // Above Left
// ^^^ ^^^^
在这些情况下,OP应该传递网格的实际大小:
int neighbourValue(int row, int column, int numColumns, char grid[][numColumns])
// ^^^^^^^^ ^^^^^^