我正在制作一个简单的脚本,它生成从 0 到 7 的 8 个随机值,并将它们存储到一个名为 random_numbers
的数组中。
这是我的尝试:
int main(int argc, char** argv) {
int random_numbers[8];
srand((unsigned)time(NULL));
for (int i = 0; i < 8; i++) {
random_numbers[i] = 1+ rand() % 8;
cout << random_numbers[i] << endl;
}
return 0;
}
这给了我重复的值。我想要 random_numbers
填充从 0 到 7 的随机值,但没有任何重复的数字。
我该怎么做?
最佳答案
生成数字 0 到 7,然后将它们洗牌。假设这实际上是 C++,而不是 C(因为 cout
),使用 std::random_shuffle
:
#include <algorithm>
#include <cstdlib>
#include <iostream>
int main()
{
int a[8] = {0, 1, 2, 3, 4, 5, 6, 7};
std::srand(unsigned(std::time(0)));
std::random_shuffle(a, a + 8);
for (int i=0; i<8; i++)
std::cout << a[i] << " ";
std::cout << std::endl;
}
注意:cppreference.com states “随机数生成器是实现定义的,但函数 std::rand
经常被使用。”我已经用 std::srand
播种了它,但显然这不是完全可移植的。
关于c++ - 从0到7生成8个唯一的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16833676/