Reputation: 493
I want to populate a grid with 1s and 0s.
My program crashes due to the random variable r. It works perfectly fine with a constant(eg: say r=8). I have used srand(time(NULL));
void initGrid(int grid[GRID_HEIGHT][GRID_WIDTH])
{
int i,j,r;
for(i=0;i<GRID_HEIGHT;i++)
{
r = rand()%10;
for(j=0;j<GRID_WIDTH;j++)
{
grid[i][j]= (i*j+i+j)%(r)<=2?1:0;
}
}
}
Upvotes: 0
Views: 59
Reputation: 156
If you want to fill it with 0 or 1, couldn't you just change it so that rand() gives the grid element it's value directly without needing to do the ternary modulus operation?
void initGrid(int grid[GRID_HEIGHT][GRID_WIDTH])
{
int i,j;
for(i=0;i<GRID_HEIGHT;i++)
{
for(j=0;j<GRID_WIDTH;j++)
{
grid[i][j]= rand()%2;
}
}
}
That would also get rid of the division by zero problem caused by (i*j+i+j)%(r)
(as stated by Weather Vane in his answer)
Upvotes: 1
Reputation: 34585
You have a "Divide by 0" error.
r = rand()%10;
gives the range of r
as 0..9
so using that 0
for the modulus in (i*j+i+j)%(r)
is causing the error.
I suggest you use
r = 1 + rand()%10;
Upvotes: 5