Random numbers in C

后端 未结 10 1380
栀梦
栀梦 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:36
    int** a;
    int i;
    printf("Enter array size: ");
    scanf("%d", &n);
    if( n < 1 ){
        printf("Size should be > 0\n\n");
        return NULL;
    }
    a = (int**)calloc(n, sizeof(int));
    for(i = 0; i < n; i++)
        a[i] = (int*)calloc(n-1, sizeof(int));
    

    Here is my array...

    0 讨论(0)
  • 2020-12-07 01:40
    srand(time(NULL));
    for(i = 0; i < n; i++){
        for(j = 0; j < (n-1); j++){
            a[i,j] = rand();
        }
    }
    

    No matter. The number are the same...

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

    srand is a function that "seeds" the random number generator. In case you don't know, random numbers in computers aren't really random. In effect, the computer just has a list of numbers that seem random in it, and you use srand to tell it where to start in that list, with each call to rand() returning the next item in the list.

    The reason you write srand(time(NULL)) is to get the random numbers to start at some point that isn't going to be the same every time you run the program (unless the programs start at the same time).

    So what you are doing here is repeatedly telling the program to restart the random number list at the same point (because the time is the same each time you go through the loop). Move the call to srand outside the loop and you will get the correct results.

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

    FAQs 13.15 to 13.20 will be of interest. And I am tempted to create a new tag for such questions.

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

    alt text

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

    Call srand() outside of the loop. You are reseeding it every iteration.

    srand() seeds the random number generator so you get a different sequence of random numbers depending on the input. Your loop runs very fast, so the call to time(NULL) always returns the same value. You are resetting to the same random sequence with every iteration. As a general rule, only call srand() once in your program.

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