-4

可能重复:
在整个范围内均匀生成随机数
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();

}
4

4 回答 4

12

执行rand() % 20并将其增加 5。

于 2011-11-18T16:35:33.050 回答
6

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

这将在同一范围内给出不同的分布。

于 2011-11-18T16:42:35.430 回答
2

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);
}
于 2011-11-18T16:44:14.090 回答
0
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

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

}
于 2011-11-18T16:38:31.320 回答