无任何重复数的随机数生成器



所以基本上我必须制作一个数组,允许用户随机生成他们选择的数字数量,并且没有一个数字是相同的。我的代码正常生成它们,但仍然会得到重复的数字,我不知道为什么,因为我想我阻止了它。我对数组还很陌生,所以这看起来可能真的很愚蠢,任何帮助都将不胜感激!我留下了很多旁注,试图分解每一节,在底部我会包括它运行时的样子。

#include <iostream>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
int numberlist[20]; //the array
int count=0,amount=0,value=0;
bool found=false;
srand(time(NULL)); //makes randomizer not the same
cout << "How many numbers to generate?" << endl;
cin>>amount; //gets user input
for(int count=0; count<amount; count++){
value = rand() % 40 + 1; //generates random number from 1-40 until amount is reached
found=false;
if(value==numberlist[count])found=true; //if value is in the array, change found from false to true
if(value!=numberlist[count] && found==false){ //if number is unique and new
numberlist[count]=value;                   //add number to array
cout << value << endl; //show the value to the screen
}
else if (found==true) {count--;} //if value is in array erase 1 from count
}
return 0;
}
//What it looks like altogether
//How many numbers to generate?
// 9 (<the users input)
//37
//5
//30
//13
//7
//18
//1
//25
//25 (The 25 is the repeating number in this case)

您的逻辑有错误

if(value==numberlist[count])found=true; //if value is in the array, change found from false to true这只是在位置等于count时检查是否没有重复,您必须遍历所有数组位置!

以下完整代码:

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int numberlist[20]; //the array
int count=0,amount=0,value=0;
bool found=false;
srand(time(NULL)); //makes randomizer not the same
cout << "How many numbers to generate?" << endl;
cin>>amount; //gets user input
for(int count=0; count<amount; count++){ 
value = rand() % 40 + 1; //generates random number from 1-40 until amount is reached
found=false;
for(int i = 0 ; i < count; i++) // iterate over all position in array
if(value==numberlist[i])found=true; //if value is in the array, change found from false to true
if(found==false){ //if number is unique and new <--- I have also fix this condition
numberlist[count]=value;                   //add number to array
cout << value << endl; //show the value to the screen
}
else if (found==true) {count--;} //if value is in array erase 1 from count
}
return 0;
}

最新更新