joh*_*eef 1 c++ variables static
我使用的是随机数生成功能,它的工作很好,但我需要重置功能变量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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我需要在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;
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用参数声明函数.例如
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;
}
Run Code Online (Sandbox Code Playgroud)