当作用域中出现条件时,如何重置函数中的变量?
How to reset a variable in a function when a condition happens in the scope?
我正在使用随机数生成函数,它工作正常,但我需要重置一个函数变量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
声明为全局变量,因为您在两个不同的函数main
和PRNG()
中引用它。
像static unsigned int nSeed = 5323;
一样声明在头文件之后。将其移出PRNG()
相关文章:
- C++变量在调用 x64 程序集函数后重置为 0
- 变量始终在函数中重置为默认值
- 为什么我的 LogError 函数会重置 GetLastError?
- 是否可以使用类的析构函数内部函数来重置值?
- 当作用域中出现条件时,如何重置函数中的变量?
- std::unique_ptr 在虚拟析构函数上重置 SIGABRT
- 重置在 lambda 函数中捕获的共享指针
- bind shared_ptr ::重置 - 找不到匹配的超载函数
- 为什么某些C++标准库“运算符<<”函数将其流宽度重置为 0
- 重置"static"类的函数的命名约定
- 函数调用重置传递的全局结构的字段
- 在不调用复制构造函数的情况下重置对象
- 递增的int在函数末尾重置
- 如何重置函数内部的静态结构
- 我必须在我自己的析构函数中手动重置shared_ptrs吗?
- 如何重置函数内部的静态向量
- 在一个函数中使用有效的 setter 进行更改会在另一个函数中重置回其旧状态
- c++在类构造函数中重置默认数组长度
- 在调用main()函数之前重置全局对象中的向量
- 调用接收对象副本的函数后,原始函数将重置