如何在c ++中生成5到25之间的随机数

far*_*oft -4 c++ random srand

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

}
Run Code Online (Sandbox Code Playgroud)

Jos*_*phH 11

rand() % 20并增加5.

  • 即使OP的问题非常模糊("随机"是什么意思?),这个答案至少应该提到由此产生的分布是有偏见的. (5认同)

Ste*_*sop 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);
Run Code Online (Sandbox Code Playgroud)

或者它也可以是:

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

这将在相同的范围内给出不同的分布.