C++ 随机数从 1 到一个非常大的数字(例如 2500 万)

2022-01-17 00:00:00 random numbers largenumber c++

你将如何制作一个生成 1 到 2500 万随机数的函数?

How would you make a function that generates a random number from 1 to 25 million?

我考虑过使用 rand() 但我认为最大数字 RAND_MAX 是 = 32000(大约)是正确的吗?

I've thought about using rand() but am I right in thinking that the maximum number, RAND_MAX is = 32000 (there about)?

有没有办法解决这个问题,一种不会降低选择非常低数字的概率并且不会增加选择高/中等数字的概率的方法?

Is there a way around this, a way that doesn't reduce the probability of picking very low numbers and doesn't increase the probability of picking high / medium numbers?

@Jamey D 的方法完全独立于 Qt.

@Jamey D 's method worked perfectly independent of Qt.

推荐答案

你可以(应该)使用新的 C++11 std::uniform_real_distribution

You could (should) use the new C++11 std::uniform_real_distribution

#include <random>

std::random_device rd;
std::mt19937 gen(rd());

std::uniform_real_distribution<> distribution(1, 25000000);

//generating a random integer:
double random = distribution(gen);

相关文章