如何在c++中生成一个介于5和25之间的随机数

How can I generate a random number between 5 and 25 in c++

本文关键字:一个 随机数 之间 c++      更新时间:2023-10-16

可能重复:
在整个范围内统一生成随机数
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;
}