如何在 C++ 的循环中生成不同的随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4926622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:55:48  来源:igfitidea点击:

How to generate different random numbers in a loop in C++?

c++loopsrandom

提问by bijlikamasla

Is it possible to generate different random number, every time loop runs. For example, i have:

每次循环运行时,是否可以生成不同的随机数。例如,我有:

for (int t=0;t<10;t++)
{
    int random_x;
    srand ( time(NULL) );
    random_x = rand() % 100;
    cout<<"\nRandom X = "<<random_x;
} 

But the problem is, it generates same random number everytime. Is it possible to generate different random numbers everytime loop runs?

但问题是,它每次都会生成相同的随机数。每次循环运行时是否可以生成不同的随机数?

IS there any possibility to reset random number initiallization as well?

是否也有可能重置随机数初始化?

回答by etarion

Don't use srandinside the loop, use it only once, e.g. at the start of main(). And srand()is exactly how you reset this.

不要srand在循环内部使用,只使用一次,例如在main(). 这srand()正是您重置它的方式。

回答by payne

You are getting the same random number each time, because you are setting a seed inside the loop. Even though you're using time(), it only changes once per second, so if your loop completes in a second (which it likely will), you'll get the same seed value each time, and the same initial random number.

您每次都获得相同的随机数,因为您在循环内设置了一个种子。即使您正在使用time(),它也每秒只更改一次,因此如果您的循环在一秒钟内完成(很可能会),您每次都会获得相同的种子值和相同的初始随机数。

Move the srand()call outside the loop (and call it only once, at the start of your app) and you should get random "random" numbers.

srand()调用移到循环之外(并且在应用程序开始时只调用一次),你应该得到随机的“随机”数字。

回答by Mr.C64

Do notuse rand(); use new C++11 facilities (e.g. std::mt19937, std::uniform_int_distribution, etc.) instead.

千万不能使用rand(); 使用新的C ++ 11级的设施(如std::mt19937std::uniform_int_distribution等)来代替。

You can use code like this (live here on Ideone):

你可以使用这样的代码(住在 Ideone 上):

#include <iostream>
#include <random>
using namespace std;

int main()
{
    // Random seed
    random_device rd;

    // Initialize Mersenne Twister pseudo-random number generator
    mt19937 gen(rd());

    // Generate pseudo-random numbers
    // uniformly distributed in range (1, 100)
    uniform_int_distribution<> dis(1, 100);

    // Generate ten pseudo-random numbers
    for (int i = 0; i < 10; i++)
    {
        int randomX = dis(gen);
        cout << "\nRandom X = " << randomX;
    }
}


P.S.

聚苯乙烯

Consider watching this video from Going Native 2013 conference for more details about rand()-related problems:

考虑观看 Going Native 2013 会议上的视频,了解有关rand()相关问题的更多详细信息:

rand() Considered Harmful

rand() 被认为是有害的

回答by Tommy Andersen

Try moving the seed srandoutside the loop like so:

尝试将种子移动到srand循环外,如下所示:

srand ( time(NULL) );
for (int t=0;t<10;t++)
{
    int random_x;
    random_x = rand() % 100;
    cout<< "\nRandom X = "<<random_x;
} 

As Mark Ransom says in the comment, moving the seed outside the loop will only help if the loop is not residing in a function you are calling several times.

正如 Mark Ransom 在评论中所说,将种子移到循环外只会在循环未驻留在您多次调用的函数中时有所帮助。

回答by user3000012

I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:

我有同样的问题好几天了。将 srand() 排除在循环之外是一个 +。另外,不要将 rand() % 100 分配给任何变量。只需在循环中 cout rand() % 100 即可。尝试这个:

    srand (time(NULL));
    (int t=0;t<10;t++)
    {
    cout << rand() % 100 << endl;
    } 

回答by Mark Ransom

Move the srandcall to the start of the program. As you have it now, the time might be the same between two consecutive calls, so the random number generator will start again at the same spot.

srand调用移至程序的开头。正如您现在所拥有的,两次连续调用之间的时间可能相同,因此随机数生成器将在同一位置再次启动。

回答by Xavier V.

You need to extract the initilization of time() out of the for loop.

您需要从 for 循环中提取 time() 的初始化。

Here is an example that will output in the windows console expected (ahah) random number.

这是一个示例,它将在 Windows 控制台中输出预期的(啊哈)随机数。

#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 100;
        std::cout << "\nRandom X = " << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}

回答by djp

The time function probably returns the same value during each iteration of the loop.

time 函数可能在循环的每次迭代期间返回相同的值。

Try initializing the random seed before the loop.

尝试在循环之前初始化随机种子。

回答by Marlon

Every iteration you are resetting the sequence of pseudorandom numbers because you are calling srandwith the same seed (since the call to timeis so frequent). Either use a different seed, or call srandoncebefore you enter the loop.

每次迭代都会重置伪随机数序列,因为您srand使用相同的种子调用(因为调用time非常频繁)。要么使用不同的种子,要么在进入循环之前调用srand一次

回答by Sarthik Garg

/*this code is written in Turbo C++
 For Visual Studio, code is in comment*/

int a[10],ct=0,x=10,y=10;    //x,y can be any value, but within the range of 
                             //array declared
randomize();                 //there is no need to use this Visual Studio
for(int i=0;i<10;i++)
{   a[i]=random(10);         //use a[i]=rand()%10 for Visual Studio
}
cout<<"\n\n";
do
{   ct=0;
    for(i=0;i<x;i++)
    {   for(int j=0;j<y;j++)
        {   if(a[i]==a[j]&&i!=j)
            {   a[j]=random(10);    //use a[i]=rand()%10 for Visual Studio
            }
            else
            {   ct++;
            }
        }
    }
}while(!(ct==(x*y)));

Well I'm not a pro in C++, but learnt it in school. I am using this algo for past 1 year to store different random values in a 1D array, but this will also work in 2D array after some changes. Any suggestions about the code are welcome.

好吧,我不是 C++ 的专家,但在学校里学过。过去 1 年我一直在使用此算法将不同的随机值存储在一维数组中,但经过一些更改后,这也适用于二维数组。欢迎任何有关代码的建议。