1

I tried to put different random number element in each array. However that 2 arrays got exactly same 10 random number. What's wrong with me and how can I solve this?

#define MAX 100
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void number(int* array)
{
    srand((long)time(NULL));
    for (int i = 0; i < 20; i++)
        array[i] = rand() % MAX + 1;

}

void printing(int* p_array)
{
    for (int i = 0; i < 20; i++)
        printf(" %d", p_array[i]);
    puts("");
}

int main(void)
{
    int score1[20];
    int score2[20];
    number(score1);
    printing(score1);
    number(score2);
    printing(score2);

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
undefined
  • 21
  • 4

3 Answers3

2
srand((long)time(NULL));

When you are doing this, you are initializing srand with a seed based on the time the line has been called. The main point of a pseudo-number generator such as srand is that, whenever the seed is the same, the generator will always return the exact same serie of values, so a program using the generator with a specific seed can reproduce the exact same results several times.

The problem is that you initialize srand two times, and that the line is run two times at the exact same time (at least at the same second on such a short program), so the seed is the same. Your two arrays are, thus, strictly identical.

Call this line only once at the beginning of your main function, and you will use only one serie of numbers instead of two identical ones, leading to your two arrays having different values.

int main(void)
{
    srand(time(NULL));

    int score1[20];
    int score2[20];
    number(score1);
    printing(score1);
    number(score2);
    printing(score2);

    return 0;
}
Izuka
  • 2,572
  • 5
  • 29
  • 34
0

As 4386427 says, the problem is your call to srand(null). It resets the random number generator. If it didn't generate the same number series, then your number generator is broken. Remove it or call it with say the current time will fix the problem.

Erik
  • 2,013
  • 11
  • 17
0

Remove this statement from the number function

srand( (unsigned int)time(NULL));

and place it in main before the calls to number.

Otherwise the expression time(NULL) could yield the same value.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335