如何在C ++中从数组中选取随机数?

时间:2018-09-21 14:33:49

标签: c++ random

int array[5];
int Random;
for (int i = 0; i <5; i++)
{
    cin>>array[i];
}
for (int j = 0; j < 5; j++)
{
    Random = array[rand() % array[j]];
}
cout << Random << endl;

这使我不断返回1,但每次我都希望输入不同的数字

2 个答案:

答案 0 :(得分:2)

兰德基本上已经过时了。
关于它有多糟糕的投诉太多了(因为正确使用它,您必须记住做几件事)。甚至佩里斯(Peris)的回答也无法校正不均匀的射程。

因此,请尝试使用功能更强大的现代随机库。尽管它的文档很难,但您无需阅读所有内容。这是一个简单的用法示例。

#include <random>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int>  array(5, 0);
    for (int i = 0; i < 5; ++i)
    {
        std::cin >> array[i];
    }

    std::random_device rd;
    std::mt19937       gen(rd());
    std::uniform_int_distribution<> dis(0, array.size() - 1);

    std::cout << array[dis(gen)];
}

注意:

rd:      Random device. Gives some initial randomness to help initialize things.
         Think of this as the `srand(time())` in the old random (but better).

mt19937: This is the algorithm used to generate the random number.
         It is initialized with some random value from rd. But it
         is a well know well understood random algorithm.

         Also be seperating this out into its own object.
         We don't have a central random number place. This means
         different applications can have their own unique random number stream.

         Note: If you want a random number stream. But the same stream
         every time (testing/debugging) then don't use the random
         device to initialize this object. Just use a nice normal
         integer and it will give a random stream of numbers but each
         time you run the application you get the same stream (which is useful
         for debugging when you don't actually want real randomness).


dis:     The main issue with the old rand() is that if just gave a number.
         It was up to the user of the number to build appropriate distributions
         and to be blunt most people either got it wrong or did not bother.
         In the random library there are several built in distributions but uniform
         is a nice easy one that is often useful (and I hope obvious).

答案 1 :(得分:0)

rand()不会返回真实随机数,而是会返回伪随机数。 这完全取决于您提供给随机生成器的初始种子。如果初始种子相同,那么从伪随机算法中得到的结果数就是相同的。

然后,您应该在每次调用(在这种情况下,是程序的每次执行)上更改rand()的初始种子。还有什么比time更好的变化价值?

注意:

代码上的

array[rand() % array[j]];行由于数组索引超出界限而极易遭受分段错误的攻击。<​​/ p>

这是解决方案。

#include <iostream>
#include <time.h>

using namespace std;

int main()
{   
    // Initialize the srand seed.
    srand (time(NULL));

    int size = 5;
    int array[size];
    int Random;
    for (int i = 0; i <5; i++)
    {
        cin>>array[i];
    }

    int index = rand() % size;
    Random = array[index];
    cout << Random << endl;
}

更新

如许多其他建议所建议的那样,您可以移至std::uniform_int_distribution以获得更好的结果。我的答案只会更新您的初始代码。