简体   繁体   English

使用随机变量会使C程序崩溃

[英]C program crashes with use of a random variable

I want to populate a grid with 1s and 0s. 我想用1和0填充网格。 My program crashes due to the random variable r. 我的程序由于随机变量r而崩溃。 It works perfectly fine with a constant(eg: say r=8). 它可以与常数完美配合(例如:说r = 8)。 I have used srand(time(NULL)); 我用过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. 您有一个“除以0”错误。

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. 给出r的范围为0..9因此对于(i*j+i+j)%(r)的模数使用0会引起误差。

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? 如果要用0或1填充它,是否可以不做三元模运算就直接更改它,以便rand()直接为网格元素提供其值?

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) 这也将消除由(i*j+i+j)%(r)引起的零除问题(如Weather Vane在他的回答中所述)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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