Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

c - function with rand initializes matrix always the same way

I have a function that should initialize the values of matrix in a random way, given a probability (in this case p(0)=1/3, p(1) = 2/3 ) The problem is that the matrix always comes out to be the same:

void init_matrix(short unsigned* m,int* n_gen)
{
    *n_gen=0;
    int i;
    for(i=0;i<N_X*N_Y;i++) {
        if( ( ( rand() % 100 ) % 3) == 0 )
            m[i]=0;
        else
            m[i]=1;
     }
}

is it because of the implementation of the rand() function? Or am I using it incorrectly? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should call srand function to initialize random number generator:

srand(time(NULL));
init_matrix(m, &n_gen); // call your function

For every value passed as argument rand() generates a different succession.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...