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

前端 未结 12 2701
忘了有多久
忘了有多久 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:27

    Random number generators are not actually random, they like most software is completely predictable. What rand does is create a different pseudo-random number each time it is called One which appears to be random. In order to use it properly you need to give it a different starting point.

    #include 
    #include 
    #include 
    
    int main ()
    {
      /* initialize random seed: */
      srand ( time(NULL) );
    
      printf("random number %d\n",rand());
      printf("random number %d\n",rand());
      printf("random number %d\n",rand());
      printf("random number %d\n",rand());
    
      return 0;
    }
    

提交回复
热议问题