How does the random number generator work in C?

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

    This is actually a FAQ on comp.lang.c. Here's the solution that they suggest:

    (int)((double)rand() / ((double) RAND_MAX + 1) * N )
    

    Where N is the ceiling of your range of random numbers. This is because the low order bits on bad C compilers are "shockingly non-random". This doesn't get around the need for using srand(). Note, however that srand( time(NULL) ) should be called outside of your loop... time() has a resolution of 1 second, so calling it inside of the loop will re-initialize your random number generator to the same seed many times in a row.

    The need for this is probably largely historical, I'm sure that modern compilers probably don't have random number generators which emit really bad random numbers, but I remember writing a program using the Borland C compiler which would cycle through about 5 numbers when I used rand() % 41 repeatedly.

提交回复
热议问题