【发布时间】:2015-01-02 17:20:33
【问题描述】:
我搜索了using time.h 获取random 种子initialization 时的问题。特别是在我的情况下,我想将 time 放在 main 函数之外。
根据 cmets 我做了一些更改。在 include as and 中包含两次后,这些错误和警告消失了:
too few arguments to function ‘random’
implicit declaration of function ‘srandom’ [-Wimplicit-function-declaration]
too few arguments to function ‘random’
一旦我将代码声明为:
#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;
...
}
它可以工作,但是它必须移到 main 之外。但如果我改为:
#include <sys/time.h>
struct timeval time;
int main(void)
{
...
}
它给了我错误:
‘time’ redeclared as different kind of symbol
在我的例子中,我正在使用 C 语言而不是 C++。当我尝试将代码移动到函数以便每次调用我的函数时接收不同的随机数时,会发生其他一些错误:
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);
}
}
显然是should be working。有人知道这里出了什么问题。所有 cmets 都受到高度赞赏。
更新:然后,从 myRandom 中取出 srandom 会使生成的值符合预期。所以,它成功了!
【问题讨论】: