如何在C ++中的特定间隔中获取随机数

0 c++ random numbers

我需要介于特定间隔之间的数字。

# include<iostream>
# include<cstdlib>
# include<ctime>
using namespace std;

int main()
{
    srand(time(0));

    for (int x = 1; x<=10; x++)
    {
        cout<<  15+ (rand()% 20)   <<endl;

    }
}
Run Code Online (Sandbox Code Playgroud)

我希望输出在15到20之间,例如[15,20],但我总是得到>或<的输出,而不是确切的间隔。

lve*_*lla 5

自该语言的2011版本以来,有一个名为的类std::uniform_int_distribution,但我认为它不能与一起使用rand(),因此您必须使用一种新的伪随机生成器,例如std::mt19937

# include<random>
# include<iostream>
# include<ctime>

using namespace std;

int main()
{
    uniform_int_distribution<> dis(15, 20);
    mt19937 gen(time(0));

    for (int x = 1; x<=10; x++)
    {
        cout<<  dis(gen)   <<endl;

    }
}
Run Code Online (Sandbox Code Playgroud)