0

I have done some search about problems when using time.h to obtain a random seed initialization. Particularly in my case, I want to place the time outside the main function.

Based on the comments I made some changes. After including twice in the include as and , these errors and warning went off:

too few arguments to function ‘random’
implicit declaration of function ‘srandom’ [-Wimplicit-function-declaration]
too few arguments to function ‘random’

Once I declared the code as:

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <unistd.h>
#include <math.h>
int main(void)
{
    struct timeval time;
    ...
}

It works, however it has to move outside main. But if I change to:

#include <sys/time.h>
struct timeval time;
int main(void)
{
    ...
}

It gives me the error:

‘time’ redeclared as different kind of symbol

In my case the implementation I am working on is in C not in C++. When I try to move the code to a function in order to receive a different random number every time my function is called, some other errors happen:

double myRandom(double dAverage,double dStddev);

double myRandom(double dAverage,double dStddev){
    int iRandom1, iRandom2;
    double dRandom1, dRandom2,result;
    long int liSampleSize;

    iRandom1=(random());
    dRandom1=(double)iRandom1 /2147483647;
    iRandom2=(random());
    dRandom2=(double)iRandom2 /2147483647;
    result= dAverage + dStddev * sqrt(-2.0 * log(dRandom1))*cos(6.28318531 * dRandom2);

    return(result);
}

int main(void){
    ...
    struct timeval time;
    gettimeofday(&time, NULL);
    srandom((unsigned int) time.tv_usec);

    for (i=0; i<liSampleSize;i++)
    {   result=myRandom(dAverage,dStddev);
    }
}

Apparently it should be working. Has somebody any idea what is wrong here. All comments are highly appreciated.

Update: Then, taking srandom out of myRandom makes the generated values as expected. So, it worked!

Community
  • 1
  • 1
Hatsune Oko
  • 206
  • 1
  • 8

1 Answers1

2

The first error is related to time.h. Including it introduces some instance called time to your global namespace.

The second is most likely because you haven't included stdlib.h.

downhillFromHere
  • 1,967
  • 11
  • 11