如何在范围内发生条件时重置函数中的变量?

问题描述 投票:0回答:2

我正在使用随机数生成函数,它工作正常但我需要重置一个函数变量nSeed并让函数在范围内发生if时重新启动,让我们说nSeed=5323

当int 5323时,如何将它返回到起始值a%16==0?我不知道怎么做。

这是一个例子:

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"
          } 
   }  
}  
c++ variables
2个回答
1
投票

首先,您需要了解变量的范围。在你的情况下,主要不知道什么是nSeed,因为它被宣布在该功能的一侧。将nSeed声明为全局变量,因为您在两个不同的函数mainPRNG()中引用它。

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


3
投票

使这项工作的一种方法是将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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.