如何生成范围内的随机数?

时间:2014-08-18 02:35:15

标签: c++ arrays random

我正在研究数组,无法弄清楚我做错了什么。

我需要输出一个数组,其中 8个随机生成的数字在5到25之间。

在对我的问题进行投票之前:/,我试图在stackoverflow上查找类似的问题,但大多数都包含使用算法或不同类型的排序技术。我不能在我的答案中使用这些技术。它应该更容易解决这个问题。

我的代码中的问题出在哪里?为什么我的循环通过数组时,我的随机数不能生成新数字?

int table[8];
int random_number= rand() % 25 + 5;

for (int i=0; i<8; i++)
{
    table[i] = random_number;
    cout << table[i] << " ";
}

当我编译并运行它时,它给了我相同数字的8倍,但是我让我的数组循环遍历每个索引,同时在其中放入一个随机数?在纸面上这应该正常工作,对吗?

有没有人可以解释我做错了什么以及为什么我的循环无法正常工作?

5 个答案:

答案 0 :(得分:4)

在c ++ 11中,您可以使用random设施

std::default_random_engine engine; // or other engine as std::mt19937
int table[8];
std::uniform_int_distribution<int> distr(5, 25);

std::generate(std::begin(table), std::end(table), [&](){ return distr(engine); });

Live example

答案 1 :(得分:3)

如我所知,在C ++中生成一个范围内的随机数并不是那么简单。在我的例子中,你需要有一个srand()和rand()函数。

#include <iostream>
#include <cstdlib>//srand and rand
#include <ctime>//time

int main()
{
    /*

    [$] srand() gives to the rand() function a new "seed", which is a starting point
    (usually random numbers are calculated by taking the previous number (or the seed))

    You could also pass another different seed from time(0), for example:
            srand(3); 
    Numbers would be generated according to the seed 3, hence numbers would be the same every time

    [#] So how can we do the opposite?

    [$] That's why we need time(0)

    [#] So what exactly is time(0)?

    [$] time(0) returns the number of seconds since the UNIX epoch.

    [#] Why is this useful?

    [$] Because every time you make your program start, the number of second will be different (because the time passes)
    and therefore also the seed and, consequently, the random numbers generated will be different every time
    unless you start the program at the same time every time, which is improbable.

    [#] Ok, thank you :)

    */

    srand(time(0));


    int _min = 5;//min
    int _max = 25;//max

    const int total_numbers = 8;//total numbers you want to generate
    int _array[total_numbers] = {0};

    int random_number = -1;

    for(int i=0; i<total_numbers; ++i)
    {
        /*
        [$]
        This formula it's not obvious to understand,
        and it's a general formula you can use to generate numbers in a range.

        rand() % NUMBER will generate a number between 0 and the NUMBER.

        In our example, we want to generate between 5 and 25.

        [#] So what is the NUMBER ?

        If you believe or not, it's ((_max - _min) + 1), which in our case is 21.

        With 21 as our NUMBER, we will have the maximum number to be 20 and the minimum number to be 0.

        If we add 5 to the random number generated, we will have the minimum number equals to 5
        and the maximum number equals to 25, agree?

        [#] Thank you, well explained :)
        */

        random_number = _min + rand() % ((_max - _min ) + 1);

        _array[i] = random_number;
    }

    //Enhanced for loop
    for(int i : _array)
        std::cout << "Random number "<< i << '\n';

    return 0;
}

答案 2 :(得分:0)

  

当我编译并运行它时,它给了我相同数字的8倍,但是我让我的数组循环遍历每个索引,同时在其中放入一个随机数?在纸面上这应该正常工作,对吗?

没有

变量就像存储盒。您可以输入值,然后您可以获得放入的值。

int random_number = rand() % 25 + 5;

此行通过执行表达式rand() % 25 + 5来计算值,并将该值放入变量random_number中。例如,它可能会计算值20将该值放入变量中。每当您从变量中检索值时,您将获得放入的最后一个数字。

table[i] = random_number;

此行接受变量random_number并检索其值(例如20)并将其分配给table[i]。重要的是,random_number如何获得其价值并不重要。你在框中加了一个值,你只会得到那个值。

如果您想要更改变量值,则必须更改它:

int random_number = rand() % 25 + 5; // create variable and set its value

random_number = rand() % 25 + 5; // set the variable's value again
random_number = rand() % 25 + 5; // set the variable's value again
random_number = rand() % 25 + 5; // set the variable's value again

如果您想要一个在评估时运行代码的实体,那么您需要一个函数:

int random_number() {
  return rand() % 25 + 5;
}

定义此功能后,您可以使用random_number()重新评估表达式:

int random_number() {
  return rand() % 25 + 5;
}

int main() {
  int table[8];

  for (int i=0; i<8; i++)
  {
    table[i] = random_number();
    cout << table[i] << " ";
  }
}

注意这里的区别:random_number()是一个函数调用,它重新运行rand() % 25 + 5表达式,而不是变量。变量只是存储您上次输入的任何数据。函数在您调用它们时会运行代码。

答案 3 :(得分:0)

假设您要生成[start,end]范围内的随机数:

rand()%end; 

在[0,end)中给出随机整数。

因此,首先在[0,(end-start)]中生成随机数,然后在此范围内添加“start”以获得所需的范围,如下所示。

[0 + start,end-start + start] = [start,end]

rand()%(end-start+1) + start;

希望这有帮助!

答案 4 :(得分:-2)

int table[8];

for (int i=0;i<8;i++)
{
   table[i]=rand() % 21 + 5;
   cout << table[i] << " ";
}