Random numbers in C

2019-01-15 18:29发布

for(i = 0; i < n; i++){
        srand(time(NULL));
        printf("%d ", time(NULL));
        for(j = 0; j < (n-1); j++){
            a[i][j] = rand();
        }
    }

I try to generate random numbers, but they are the same... I try srand(i * time(NULL)). No matter.. What should i do?

Array declaration:

int** a;
int i;
printf("Enter array size: ");
scanf("%d", &n);

a = (int**)calloc(n, sizeof(int));
for(i = 0; i < n; i++)
    a[i] = (int*)calloc(n-1, sizeof(int));

标签: c random srand
10条回答
霸刀☆藐视天下
2楼-- · 2019-01-15 18:33
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.

查看更多
男人必须洒脱
3楼-- · 2019-01-15 18:34
兄弟一词,经得起流年.
4楼-- · 2019-01-15 18:35
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...

查看更多
相关推荐>>
5楼-- · 2019-01-15 18:38

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.

查看更多
太酷不给撩
6楼-- · 2019-01-15 18:41

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

查看更多
我命由我不由天
7楼-- · 2019-01-15 18:46

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

查看更多
登录 后发表回答