问题
I have an error somewhere in my code, I think I am entering an infinite loop. Basically I get a matrix and two indexes, i,j, and i need to count how many neighbors around [i][j] have a value of 1 or 2.
this is my code:
int number_of_living_neighbors(matrix mat,int i, int j, int n,int m)
{
int counter=0,row_index=0,column_index=0;
for(row_index=i-1;row_index<=i+1;row_index++)
{
for(column_index=j-1;column_index=j+1;column_index++)
{
if((row_index>=0)&&(row_index<n)&&(column_index>=0)&&(column_index<m))
{
if((mat[row_index][column_index]==1)||(mat[row_index][column_index]==2))
counter++;
if((row_index==i)&&(column_index==j)&&(mat[i][j]==1))
counter--;
}
}
}
printf("The number of living neighbors is %d", counter);
return counter;
}
it doesnt print anything. mat is the matrix i get, i,j are the pointers, n is number of rows, m is number of columns.
回答1:
for(column_index = j-1 ; column_index = j+1; column_index++)
Your condition contains an assignment, not a comparison. You probably want to use <=
instead of =
:
for(column_index = j-1 ; column_index <= j+1; column_index++)
来源:https://stackoverflow.com/questions/14171466/conways-game-of-life-counting-neighbors