简体   繁体   English

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

[英]How to generate random numbers in a range?

I'm studying arrays and can't figure out what I'm doing wrong. 我正在研究数组,无法弄清楚我在做什么错。

I need to output an array with 8 random generated numbers between 5 and 25. 我需要输出一个数组,其中包含5到25之间的8个随机生成的数字。

Before down voting my question : /, I tried looking already for similar questions on stackoverflow but most of them contain the use of algorithm's or different kinds of sort-techniques. 在否决我的问题:/之前,我已经尝试过寻找关于stackoverflow的类似问题,但是其中大多数都包含使用算法或不同种类的排序技术。 I cannot use those technique's in my answer. 我不能在回答中使用那些技术。 It 'should' be easier to solve this. 解决起来应该更容易。

Where is the problem in my code and why doesn't my random number generate a new number while i'm looping trough the array? 我的代码中的问题在哪里?为什么我在遍历数组时随机数为什么不生成新数字?

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

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

As I compile and run it, it gives me 8 times the same number, however I'm letting my array loop through each single index, while putting a random number in it? 当我编译并运行它时,它给了我8倍的相同数字,但是我让数组在每个单个索引中循环,同时在其中放置了一个随机数? On paper this should work normally, right? 在纸上这应该正常工作,对吗?

Is there anyone who can explain what I did wrong and why my loop is not working correctly? 有谁能解释我做错了什么以及为什么我的循环无法正常工作?

In c++11, with random facilities you may do 在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 现场例子

Generating random numbers in a range in C++ is not so trivial, as I know. 据我所知,在C ++中生成一定范围内的随机数并不是一件容易的事。 In my example, you need to have a srand() and rand() function. 在我的示例中,您需要具有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;
}

As I compile and run it, it gives me 8 times the same number, however I'm letting my array loop through each single index, while putting a random number in it? 当我编译并运行它时,它给了我8倍的相同数字,但是我让数组在每个单个索引中循环,同时在其中放置了一个随机数? On paper this should work normally, right? 在纸上这应该正常工作,对吗?

No. 没有。

Variables are like storage boxes. 变量就像存储盒。 You can put values in and then later you can get the value you put in back out. 您可以输入值,然后再取回输入的值。

int random_number = rand() % 25 + 5;

This line computes a value by executing the expression rand() % 25 + 5 and puts that value into the variable random_number . 该行通过执行表达式rand() % 25 + 5计算一个值,并将该值放入变量random_number For example, maybe it computes the value 20 puts that value in the variable. 例如,也许它计算值20 ,然后将该值放入变量中。 Whenever you retrieve the value from the variable you will get the last number that was put in. 每当您从变量中检索值时,您都会获得最后输入的数字。

table[i] = random_number;

This line takes the variable random_number and retrieves its value (say, 20 ) and assigns it to table[i] . 该行采用变量random_number并获取其值(例如20 )并将其分配给table[i] The important bit is that it does not matter here how random_number got its value. 重要的一点是,这里random_number的值如何无关紧要。 You put a value in the box and you'll only get that value back. 您在框中输入一个值,然后只会取回该值。

If you want a variable's value to change then you have to change it: 如果要更改变量的值,则必须更改它:

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

If you want an entity that runs code when evaluated then you want a function: 如果要一个在评估时运行代码的实体,则需要一个函数:

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

After defining this function you can use random_number() to reevaluate the expression: 定义此函数后,可以使用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] << " ";
  }
}

Note the difference here: random_number() is a function call which re-runs that rand() % 25 + 5 expression, and not a variable. 注意这里的区别: random_number()是一个函数调用,它将重新运行rand() % 25 + 5表达式,而不是变量。 Variables are just storage for whatever data you last put in. Functions run code when you call them. 变量只是存储您最后放入的任何数据。函数在调用它们时将运行代码。

suppose you want to generate random numbers in the range [start, end]: 假设您要生成[开始,结束]范围内的随机数:

rand()%end; 

gives you random integer in [0, end). 给您[[0,end)中的随机整数。

So, first you generate random number in [0, (end-start)] and then add 'start' to this range to get the desired range as shown below. 因此,首先您需要在[0,(end-start)]中生成一个随机数,然后在该范围内添加“ start”以获得所需范围,如下所示。

[0+start, end-start+start] = [start, end] [0+开始,结束开始+开始] = [开始,结束]

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

hope this helps! 希望这可以帮助!

int table[8];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM