我已经用3个随机整数编码了一个数组。关键是虽然我希望3个随机整数不同于彼此(唯一的随机数)。我的问题是,即使数字是独一无二的,我仍然从他们那里得到一个“不好的”读数。随着时间的推移,我随机播放了数字(NULL),正因为如此,我在每个声明之间放置了一个Sleep(x)函数以增加数字的多样性。以下代码是我的main()函数中的所有代码。出于测试目的,我没有在我的代码中包含break语句,所以我可以一遍又一遍地测试程序。在数组中生成唯一的随机数C++
srand((unsigned)time(NULL));
while(true)
{
//Generate 3 numbers
int a = rand() % 7 + 1;
Sleep(1000);
int b = rand() % 8 + 1;
Sleep(1000);
int c = rand() % 9 + 1;
int array[3] = { a , b , c };
//Check the numbers to make sure none of them equal each other
if((array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]))
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "bad" << endl;
system("pause");
system("cls");
}
else
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "good" << endl;
system("pause");
system("cls");
}
}
system("pause");
return 0;
'睡眠'调用不会改变生成的数字。只有'srand(time(NULL))'运行时才会检查时间。 – programmerjake 2014-09-27 00:09:20
请注意,对'srand'的调用是随机数生成器的种子。每次调用'rand'时都不会使用单独的种子。所以,睡眠是没有意义的。 – Pradhan 2014-09-27 00:09:30
要生成唯一的数字,对于相对较小的固定集合,最简单/可靠的方法之一是创建一个* allowed *值的数组,然后对数组进行随机洗牌并获取前N个值。例如,给定一个数组{1,2,3,4,5,6,7,8,9},然后使用arr [0],arr [1],arr [2]等。有很多问题/适合并推荐这种(Fisher-Yates)混洗方法的答案。 – user2864740 2014-09-27 00:15:22