【问题标题】:declare struct timeval time inside a function在函数内声明 struct timeval time
【发布时间】: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 会使生成的值符合预期。所以,它成功了!

【问题讨论】:

    标签: c random time struct


    【解决方案1】:

    第一个错误与time.h 有关。包含它会在您的全局命名空间中引入一些名为 time 的实例。

    第二个很可能是因为你没有包含stdlib.h

    【讨论】:

    • 我更改了时间以两种方式添加。这很奇怪,但有效。
    猜你喜欢
    • 2012-04-23
    • 2013-11-26
    • 1970-01-01
    • 2019-12-05
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多