Why do I always get the same sequence of random numbers with rand()?

前端 未结 12 2389
忘了有多久
忘了有多久 2020-11-21 06:06

This is the first time I\'m trying random numbers with C (I miss C#). Here is my code:

int i, j = 0;
for(i = 0; i <= 10; i++) {
    j = rand();
    printf         


        
12条回答
  •  你的背包
    2020-11-21 06:31

    You have to seed it. Seeding it with the time is a good idea:

    srand()

    #include 
    #include 
    #include 
    
    int main ()
    {
      srand ( time(NULL) );
      printf ("Random Number: %d\n", rand() %100);
      return 0;
    }
    

    You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().

    Edit

    Due to comments

    rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.

提交回复
热议问题