随机数未达到限制

Random Numbers aren't reaching limit

本文关键字:未达到 随机数      更新时间:2023-10-16

我正在为 110,000 到 320,000 之间的数字创建一个随机数生成器。当我运行它时,没有数字超过 150,000。有没有办法确保生成超过 150,000 的数字?即使生成数千个数字也不起作用。我知道我有很多东西。这是代码:

#include <stdlib.h>
#include <iostream>
#include <Windows.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#include <conio.h>
#include <ctime>
#include <random>
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand((unsigned) time(0));
int randomNumber;
for (int index = 0; index < 500; index++) {
randomNumber = (rand() % 320000) + 110000;
cout << randomNumber << endl;
}
}

正如约翰所指出的。您可以使用更新的随机数生成器更易于操作。

改编C++ Reference about uniform_int_distribution代码 因为您的用例很简单:

#include <iostream>
#include <random>
int main(void) {
std::random_device rd;  // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(110000, 320000);

for (int n=0; n<10; ++n)
// Use `distrib` to transform the random unsigned int generated by
// gen into an int in [110000, 320000]
std::cout << distrib(gen) << ' ';
std::cout << 'n';
}