How does the random number generator work in C?

后端 未结 6 902
终归单人心
终归单人心 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:03

    rand() generates only pseudorandom numbers. This means that every time you run your code you will get exactly the same sequence of numbers.

    Consider using

    srand(time(NULL))
    

    to get every time different numbers. In fact a possible implementation for rand is

    next = next * 1103515245 + 12345;
    return (UINT32)(next>>16) & RAND_MAX;
    

    where next is defined as

    static UINT32 next = 1;
    

    Calling srand() has the effect of changing the initial value of next, thus changing the "next" value you get as result.

提交回复
热议问题