gpt4 book ai didi

c++ - 如何每n次重置一个函数变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:07 26 4
gpt4 key购买 nike

我正在使用随机数生成函数,它工作正常,但我需要每 n 次重置函数变量 nSeed,比方说 nSeed= 5323 .. 我怎样才能将它返回到它的起始值 53235 操作我不知道该怎么做..这是一个例子:

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"
}
}
}

注意:我需要在 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;
}

关于c++ - 如何每n次重置一个函数变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com