如何在c++中生成一个介于5和25之间的随机数
How can I generate a random number between 5 and 25 in c++
可能重复:
在整个范围内统一生成随机数
C++随机浮动
如何在c++中生成一个介于5和25之间的随机数?
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void main() {
int number;
int randomNum;
srand(time(NULL));
randomNum = rand();
}
rand() % 20
并将其递增5。
在C++11中:
#include <random>
std::default_random_engine re;
re.seed(time(NULL)); // or whatever seed
std::uniform_int_distribution<int> uni(5, 25); // 5-25 *inclusive*
int randomNum = uni(re);
或者它也可以是:
std::uniform_int_distribution<int> d5(1, 5); // 1-5 inclusive
int randomNum = d5(re) + d5(re) + d5(re) + d5(re) + d5(re);
这将在相同范围上给出不同的分布。
C++方式:
#include <random>
typedef std::mt19937 rng_type; // pick your favourite (i.e. this one)
std::uniform_int_distribution<rng_type::result_type> udist(5, 25);
rng_type rng;
int main()
{
// seed rng first!
rng_type::result_type random_number = udist(rng);
}
#include <cstdlib>
#include <time.h>
using namespace std;
void main() {
int number;
int randomNum;
srand(time(NULL));
number = rand() % 20;
cout << (number) << endl;
}
相关文章:
- 如何在 c++ 中从数组中选择一个随机数?
- 从大范围内生成一个随机数,但从大范围的中间开始生成较小的范围
- 如何在C++中创建数字列表,以便它可以选择一个随机数?
- 在[0,1)C 之间生成一个随机数
- 在此过程中的纸牌游戏程序.不知道为什么我会得到一个随机数-858993460
- 为什么递增指针会给出一个随机数,而不是内存地址
- 如何使用Linux GetRandom系统调用来在范围内生成一个随机数
- visual如何在C++中创建一个随机数数组
- 选择一个随机方块并生成一个随机数
- 在一个间隔内生成一个随机数,但某些数字除外:EXC_BAD_ACCESS
- 当你复制一个随机数引擎和随机数分布时会发生什么?
- 给一个数组一个随机数
- 从整数列表中选择一个随机数
- 提供的示例代码返回一个随机数,即使在抛出异常之后也是如此(提供的代码)
- 如何使用openssl获得一个随机数
- 为什么在头文件的第一行放一个随机数
- C++和Qt:不要在x分钟内选择一个随机数
- 随机数生成器不会给我一个随机数
- 有没有一种方法可以让我从0-10亿中得到一个随机数
- 构造函数中变量的启动不起作用,而是给我一个随机数