简体   繁体   中英

C program crashes with use of a random variable

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;
        }
    }
}

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;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM