簡體   English   中英

在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 shuffle對其進行隨機排序。 然后只取前10個數字。

請注意,在do-while循環開始時,您不會將Duplicate初始化為false,這意味着在您擁有一個重復的隨機數之后-Duplicate設置為true並因此永遠永遠為真-因此,您的do-while循環將永遠運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM