在C++中生成不同的随机数
Generating Distinct Random Numbers in C++
对于编程作业的一部分,我需要生成多组 10 个数字,范围为 1 到 50,每个单独的集合中没有重复,因此我创建了以下代码:
int Numbers[10]; //array to store the random numbers in
bool Duplicate; //variable to check or number is already used
srand(time(NULL)); //seeding the random number generator
// do while loop used to allow user to generate multiple sets
do {
Duplicate = false; // set check to false
//for loop to generate a complete set of 10 random numbers
for (int I = 0; I < 10; I++)
{
// do while loop used to generate random numbers until a distinct random number is generated
do
{
Numbers[I] = (rand()%50) + 1; // generates a random number 1 - 50 and stores it into Numbers[I]
// for loop used to check the other numbers in set for any repeats
for (int J = I - 1; J > -1; J--) // works backwards from the recently generated element to element 0
if (Numbers[I] == Numbers[J]) //checks if number is already used
Duplicate = true; //sets Duplicate to true to indicate there is a repeat
} while (Duplicate); //loops until a new, distinct number is generated
}
//at this point in the program we should have an array Numbers[] with a set of 10 unique random numbers 1 - 50
// loop to print numbers to the screen
for (int I = 0; I < 10; I++)
cout << Numbers[I] << " "; // printing the element to the screen
cout << endl;
cout << "Do you want to run the program again (Y/N): "; // Asks user if they want to create another set of 10 numbers
char Answer; // used to store users answer
cin >> Answer; // stores users answer
} while (Answer == 'Y' || Answer == 'y'); // loop program if the user wants to generate another set
但是,我似乎在使用生成随机数的 do while 循环时遇到问题,直到生成新的不同数字。经过一些测试和修补,我发现我以某种方式在那里创建了一个无限循环,无法找出问题所在。
我认为可能导致问题的一些想法:-rand 函数如何更改种子,是否更改种子以创建新的伪随机数?-我的 for 循环是否用于检查重复是否超出数组的边界?
任何建议和提示将不胜感激。
您忘记将Duplicate
重置回false
。第一次设置为true
时,它保持true
,启用无限do...while
循环。
从 1 到 50 的有序数组开始,然后通过 Fisher-Yates 洗牌进行洗牌。然后只取前 10 个数字。
请注意,在do-while循环开始时,您不会将Duplicat重新初始化为false,这意味着在您有一个重复的随机数之后 - 重复设置为true并永远保持true,因此 - 您的do-while循环将永远运行。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- if数组上的随机数
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 半随机数生成C++
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 具有随机数的二维数组不会更改
- 随机数未达到限制
- 我想生成许多矩阵并用随机数填充它
- <random>在实践中应该实际使用哪个随机数引擎? std::mt19937?
- 制作具有平均值的随机数生成器
- 为什么 rand 不在我的代码中生成随机数?
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- 从给定种子生成相同的随机数序列C++
- 随机数生成函数说明
- C++ 尝试生成随机数时弹出警告帮助?
- 尝试在 c++ 中创建随机数生成器并收到错误
- 从给定的随机数组值生成随机数 Arduino程序C++
- 如何在个人计算机和群集 (c++) 上生成相同的随机数