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:48
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...

查看更多
We Are One
3楼-- · 2019-01-15 18:55

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.

查看更多
▲ chillily
4楼-- · 2019-01-15 18: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.

查看更多
劫难
5楼-- · 2019-01-15 18:57

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.

查看更多
登录 后发表回答