2

I need to generate two random numbers of n-digits in a C program using a function. I am getting same values for both variables num1 and num2. Is it because of the faster processor that the instructions are executed without a precise change in time point by the srand() and both values are same? Can I add a time delay to get different values?

I am using two generate functions, one without srand() to get a different value. Does any other optimal solution exist?

long generate(int n)
{
  int a[n];
  srand(time(0));
  a[0] = rand() % 9 + 1;
  for (int i = 1; i<n; i++)
    a[i] = rand() % 10;

  long num = 0;
  for (int i = 0; i < n; i++)
    num = 10 * num + a[i];
  return num;
}

int main()
{
  int num1 = generate(5);
  int num2 = generate(5);
  printf("%ld   %ld",a,b);  
  return 0;
 }
user2736738
  • 30,591
  • 5
  • 42
  • 56

0 Answers0