1

I have a function generating random numbers. Why does it always generate the same ones? I tried running the algorithm several times but always get the same results.

#ifndef UTIL_H
#define UTIL_H

#include <time.h>
#include <sys/time.h>
#include <stdlib.h>

#define MIN 0
#define MAX 100000


void randomArray (double *array, int length)
{
    int i ;  
    for (i = 0; i < length; i++) 
    {
        array[i] = (double) (rand () /
                   (((double) RAND_MAX + 1) / (double) (MAX - MIN + 1))) + MIN;
    }
}

int main(void) 
{
    int i;
    double test_array[9];

    randomArray(test_array,  9);    

    for(i = 0; i < 9; i++)
        printf("%f ", test_array[i]);
    printf("\n");

    return 0;
}
yulian
  • 1,601
  • 3
  • 21
  • 49

2 Answers2

6

You need to seed the rand function. Use srand(time(NULL)) in the beginning of your main.

simonc
  • 41,632
  • 12
  • 85
  • 103
LeatherFace
  • 478
  • 2
  • 11
1

There are 3 problems in your code:

1) Add srand to your main() function:

int main(void) {
    int i;
    double test_array[9];

    srand (time(NULL));        // here it is

    randomArray(test_array,  9);

    for(i = 0; i < 9; i++)
        printf("%f ", test_array[i]);
    printf("\n");

    return 0;
}

2) Add an stdio.h library for using printf():

#include <stdio.h>

3) There is unterminated #ifndef that will couse an error when compiling. Add #endif:

#ifndef UTIL_H
#define UTIL_H
#endif             // here it is
yulian
  • 1,601
  • 3
  • 21
  • 49