我需要在 C++ 中生成随机非重复数字数组,在这部分代码中,我使用 srand 函数生成随机数,但有些数字是重复的。主要任务是为彩票生成随机数,所以我需要生成数字直到golden number,标记为int golden。
#include <cstdlib> #include <ctime> #include <iostream> using namespace std; int main() { int golden = 31; int i = 0; int array[35]; srand((unsigned)time(0)); while(i != golden){ array[i] = (rand()%75)+1; cout << array[i] << endl; i++; } }
最佳答案
一种策略是用从 1 到 75 的数字填充一个数组,然后使用 std::random_shuffle()
在上面。然后,您可以从数组中读取数字,直到找到黄金数字。
关于c++ - 在C++中生成随机非重复数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878202/