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

那年仲夏 提交于 2019-12-13 11:25:15

问题


Possible Duplicate:
Generate Random numbers uniformly over entire range
C++ random float

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

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    randomNum = rand();

}

回答1:


Do rand() % 20 and increment it by 5.




回答2:


In 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);

Or it could just as well be:

std::uniform_int_distribution<int> d5(1, 5); // 1-5 inclusive
int randomNum = d5(re) + d5(re) + d5(re) + d5(re) + d5(re);

which would give a different distribution on the same range.




回答3:


The C++ way:

#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);
}



回答4:


#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    number = rand() % 20;
cout << (number) << endl;

}


来源:https://stackoverflow.com/questions/8185699/how-can-i-generate-a-random-number-between-5-and-25-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!