How does the random number generator work in C?

后端 未结 6 855
终归单人心
终归单人心 2021-01-23 06:29

I\'m trying to generate random number between 0 and 40(inclusive). So the code I Implemented is this-

 y=rand()%41;

However everytime I click c

6条回答
  •  长情又很酷
    2021-01-23 07:17

    The algorithm used for rand is unspecified by the C Standard,

    By specification, if you don't call srand before a call to rand in your program, it is as if srand(1) was called: the seed value will be 1 at every execution of the program and the generated sequence will be always the same.

    A common way to have different seeds for different executions of the program is to use a seed which depends on the current time like:

    srand(time(NULL));  
    

提交回复
热议问题