我正在使用一个随机数生成函数,但工作正常,但我需要每隔 n次次重置一个函数变量 nSeed ,比方说 nSeed = 5323 ..如何将其返回到其初始值 5323 每个的5个操作,我不确定该怎么做..这是一个示例:

unsigned int PRNG()

{
    static unsigned int nSeed = 5323;
    nSeed = (8253729 * nSeed + 2396403);
    return nSeed  % 32767;
}

int main()
{
   int count=0;
   while(count<10)
   {
       count=count+1;
       cout<<PRNG()<<endl;

          if(count==5)
          {
               nSeed= 5323;   //here's the problem, "Error nSeed wasn't declared in the scoop"
          }
   }
}

注意:我需要在瓢中声明计数器,而不是在函数中声明。

最佳答案

只需使用另一个静态变量。例如

unsigned int PRNG()
{
    const unsigned int INITIAL_SEED = 5323;
    static unsigned int i;
    static unsigned int nSeed;

    if ( i++ % 5 == 0 )
    {
        nSeed = INITIAL_SEED;
        i = 1;
    }

    nSeed = (8253729 * nSeed + 2396403);

    return nSeed  % 32767;
}

另一种方法是使用参数声明函数。例如
unsigned int PRNG( bool reset )
{
    const unsigned int INITIAL_SEED = 5323;
    static unsigned int nSeed = INITIAL_SEED;

    if ( reset ) nSeed = INITIAL_SEED;

    nSeed = (8253729 * nSeed + 2396403);

    return nSeed  % 32767;
}

10-07 13:35