如何在 c++ 中生成 0 到 4 之间的随机数

How can I generate a random number between 0 and 4 in c++?

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

可能的重复项:
如何从范围内生成随机数 - C

我想生成一个介于 0 和 4

之间的随机数(包括 0 和 4)。 如何在 c++ 中执行此操作?

你可以调用 std::rand() ,使用取模运算符将范围限制为所需的范围。

std::rand()%5

您还可以查看新的 C++11 随机数生成实用程序

为了完整起见,我向您展示了一个使用新random工具的 C++11 解决方案:

#include <random>
#include <ctime> 
int main() {
    std::minstd_rand generator(std::time(0)); 
    std::uniform_int_distribution<> dist(0, 4);
    int nextRandomInt = dist(generator);
    return 0;
}