当作用域中出现条件时,如何重置函数中的变量?

How to reset a variable in a function when a condition happens in the scope?

本文关键字:函数 何重置 变量 作用域 条件      更新时间:2023-10-16

我正在使用随机数生成函数,它工作正常,但我需要重置一个函数变量nSeed,并在作用域中发生if时让函数重新开始,假设nSeed=5323.

当 inta%16==0时,我怎样才能5323将其返回到其起始值?我不知道该怎么做。

下面是一个示例:

unsigned int PRNG()  
{  
static unsigned int nSeed = 5323;  
nSeed = (8253729 * nSeed + 2396403);  
return nSeed  % 32767;
}  
int main()
{
int count=0;  
int a=3;
int b=5;
while(count<1000)  
{  
count=count+1; 
a=a+b; 
cout<<PRNG()<<endl;  
if(a%16==0)
{  
nSeed= 5323;   //here's the problem, "Error nSeed wasn't 
//declared in the scoop"
} 
}  
}  

完成这项工作的一种方法是将PRNG函数放在类中:

struct PRNG {
static unsigned int nSeed;
unsigned int operator()()
{
nSeed = (8253729 * nSeed + 2396403);
return nSeed % 32767;
}
};
unsigned int PRNG::nSeed{5323};
int main()
{
int count = 0;
int a = 3;
int b = 5;
while(count < 1000)
{
count = count + 1;
a = a + b;
cout << PRNG()() << endl;
if(a % 16 == 0)
{
PRNG::nSeed = 5323;
}
}
}

或者,如果您不想要静态变量:

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

int main()
{
PRNG prng;
int count = 0;
int a = 3;
int b = 5;
while(count < 1000)
{
count = count + 1;
a = a + b;
cout << prng() << endl;
if(a % 16 == 0)
{
prng.nSeed = 5323;
}
}
}

或者,使用 lambda:

int main()
{
unsigned int nSeed{5323};
auto prng = [&nSeed](){ 
return (nSeed = 8253729 * nSeed + 2396403) % 32767; 
};
int count = 0;
int a = 3;
int b = 5;
while(count < 1000)
{
count = count + 1;
a = a + b;
cout << prng() << endl;
if(a % 16 == 0)
{
nSeed = 5323;
}
}
}

首先,您需要了解变量的作用域。在你的例子中,main不知道什么是nSeed,因为它被声明在该函数的外部。将nSeed声明为全局变量,因为您在两个不同的函数mainPRNG()中引用它。

static unsigned int nSeed = 5323;一样声明在头文件之后。将其移出PRNG()