C++ 如何生成包含两个值的随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40275512/
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 15:21:56  来源:igfitidea点击:

How to generate random numbers between 2 values, inclusive?

c++randomuser-input

提问by bluthunder

I need help figuring out how to generate a set amount of random numbers between two user-inputted values, inclusively. Just so you know, I have searched for this but am not finding what I have just stated. Here is my code:

我需要帮助弄清楚如何在两个用户输入的值之间生成一定数量的随机数,包括。只是你知道,我已经搜索过这个,但没有找到我刚才所说的。这是我的代码:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    int userBeg, userEnd, outPut;

    cout << "Enter a start value: ";
    cin >> userBeg;
    cout << "Enter an end value: ";
    cin >> userEnd;

    srand(time(NULL)); //generates random seed val

    for (int i = 0; i < 5; i++) {
      //prints number between user input, inclusive
    outPut = rand()%((userEnd - userBeg) + 1); 
    cout << outPut << "  ";
    }//end for

    return 0;
}//end main 

I'm confused with the output I get for the following ranges: 1-100 yield output numbers which fall in-between, but not including, the boundaries such as 50, 97, 24, 59, 22. But, 10-20 yield numbers such as 1, 14, 6, 12, 13. Here, the output is outside of the boundaries as well as in-between them. What am I doing wrong?

我对以下范围的输出感到困惑:1-100 产量输出数字介于两者之间,但不包括 50、97、24、59、22 等边界。但是,10-20 产量数字,例如 1, 14, 6, 12, 13。在这里,输出在边界之外以及它们之间。我究竟做错了什么?

Thank you in advance for your help!

预先感谢您的帮助!

回答by Paul Rooney

Using the c++11 randomlibrary.

使用 c++11random库。

You could use std::default_random_engine(or any other random engine) with std::uniform_int_distribution.

您可以将std::default_random_engine(或任何其他随机引擎)与std::uniform_int_distribution.

The values you pass to std::uniform_int_distributionwill be the lower and upper bounds of your random range.

您传递给的值std::uniform_int_distribution将是您的随机范围的下限和上限。

e.g.

例如

#include <iostream>
#include <random>

int main()
{
    const int nrolls = 100;

    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(0,9);

    int p[nrolls]={};

    for (int i=0; i<nrolls; ++i)
    {
        p[i] = distribution(generator);
    }

    std::cout << "uniform_int_distribution (0,9):" << '\n';
    for (int i=0; i<nrolls; ++i)
    {
        std::cout << i << ": " << p[i] << '\n';
    }
}

If you wish to seed the random engine, create it like.

如果您希望为随机引擎设置种子,请创建它。

unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

std::default_random_engine generator(seed);

回答by karastojko

randreturns number between 0 and RAND_MAX. By taking modulo userEnd - userBeg + 1the boundaries will be limited to 0 and userEnd - userBeg. If the random number should be within given boundaries, then userBegshould be added, so the calculus becomes

rand返回 0 到 之间的数字RAND_MAX。通过取模userEnd - userBeg + 1,边界将被限制为 0 和userEnd - userBeg。如果随机数应该在给定的边界内,那么userBeg应该相加,所以微积分变成

    outPut = rand()%((userEnd - userBeg) + 1) + userBeg; 

回答by Carl

For the rand to work you need to do:

要使兰特工作,您需要执行以下操作:

#include <cstdlib>

int main() {

    int Min = 103;
    int Max = 113;

    int Number = std::rand() % (Max + 1 - Min) + Min;

    return 0;
}

I omitted the cinfor clarity. (Max + 1 - Min) makes it inclusive. + Min sets the minimum value!

cin为了清楚起见,我省略了。(Max + 1 - Min) 使其具有包容性。+ Min 设置最小值!

So stuffed into a function you may use:

所以塞进一个你可能会用到的函数中:

int randint(int Min, int Max) {
    return std::rand() % (Max + 1 - Min) + Min;
}

After testing it works with negative numbers as well as positive.

测试后,它适用于负数和正数。

Sample outputs (with a loop and cout):

示例输出(带有循环和 cout):

11-23

11-23

The number is: 13
The number is: 18
The number is: 14
The number is: 17
The number is: 18
The number is: 18
The number is: 23
The number is: 15
The number is: 11
The number is: 22
The number is: 22
The number is: 11
The number is: 22
The number is: 16
The number is: 14
The number is: 21
The number is: 16
The number is: 19
The number is: 15
The number is: 13
The number is: 17

1239-1242

1239-1242

The number is: 1240
The number is: 1242
The number is: 1239
The number is: 1241
The number is: 1241
The number is: 1241
The number is: 1239
The number is: 1240
The number is: 1240
The number is: 1240
The number is: 1242
The number is: 1240
The number is: 1242

回答by kh?i nguy?n

It's still experimental, but it is exactly what you want

它仍然是实验性的,但它正是你想要的

http://en.cppreference.com/w/cpp/experimental/randint

http://en.cppreference.com/w/cpp/experimental/randint

#include <iostream>
#include <experimental/random>

int main()
{
    int random_number = std::experimental::randint(100, 999);
    std::cout << "random 3-digit number: " << random_number << '\n';
}

Edited: it's really random http://en.cppreference.com/w/cpp/numeric/random

编辑:它真的是随机的http://en.cppreference.com/w/cpp/numeric/random