Random numbers in C

后端 未结 10 1381
栀梦
栀梦 2020-12-07 01:26
for(i = 0; i < n; i++){
        srand(time(NULL));
        printf(\"%d \", time(NULL));
        for(j = 0; j < (n-1); j++){
            a[i][j] = rand();
              


        
相关标签:
10条回答
  • 2020-12-07 01:54
    srand(time(NULL)); 
    
    for(i = 0; i < n; i++){         
            printf("%d ", time(NULL)); 
            for(j = 0; j < (n-1); j++){ 
                a[i,j] = rand(); 
            } 
        } 
    

    Call srand once outside the loop.

    0 讨论(0)
  • 2020-12-07 01:56

    You need to call srand() before entering the loop. srand() initializes the radnom number generator with the given seed and generates unique sequence of random numbers for this seed.

    Your loop executes very fast so every call to time(NULL) yields the same time (measured in seconds) - hence you initialize random number generator with the same seed on every loop iteration.

    0 讨论(0)
  • 2020-12-07 01:58

    Don't call srand() every time through the loop - just do it once beforehand.

    0 讨论(0)
  • 2020-12-07 02:00

    Sergey, you did not get an error message with the a[i,j] version simply because this is a perfectly valid expression. The comma operator evaluates the sub-expressions from left to right and returns the value of the last expression. Thus, writing a[i,j] is identical to a[j]. What you received in the print was the value of the pointer to the j-th vector in your matrix.

    0 讨论(0)
提交回复
热议问题