2015-10-28 73 views
1

我正在嘗試編寫一個程序,該程序從包含五種不同水果或蔬菜的數組中隨機選擇三個項目,然後將隨機選擇的內容顯示給用戶。現在我無法理解爲什麼我的輸出是不相符的,因爲有時當我運行它,我會得到這樣的事情:使用for循環顯示內容

This bundle contains the following: 


Broccoli 

與前兩個項目缺少,有時我會得到這樣的:

This bundle contains the following: 
Tomato 
Tomato 
Tomato 

這是我目前遇到的麻煩的代碼部分:

void BoxOfProduce::output() { 

     cout << "This bundle contains the following: " << endl; 

     // Use this so it will be truly random 
     srand(time(0)); 

     for (int f = 0; f < 3; f++) { 

      // Here were making the random number 
      int boxee = rand() % 5; 

      // Adding the content to the box 
      Box[f] = Box[boxee]; 

      // Now were calling on the function to display the content 
      displayWord(boxee); 

     } // End of for loop 

    } // End of output() 


    void BoxOfProduce::displayWord(int boxee) { 

     cout << Box[boxee] << endl; 

    } 


int main() { 

    BoxOfProduce b1; 
    b1.input(); 
    b1.output(); 

有人可以幫助我瞭解爲什麼我得到這個輸出?謝謝!

+1

'函數srand(時間(0))'是不是真的隨機的,這是一個僞隨機生成器。另外考慮使用std :: random代替。 – Daffyd

+0

爲輸入法添加代碼。 //將內容添加到框 Box [f] = Box [boxee];似乎很腥......你重寫同一個數組的內容。 – Nandu

回答

1

不這樣做,像你這樣做:) 像@ John3136指出,你搞亂了你的變量箱..

void BoxOfProduce::output() 
{ 

    srand(time(NULL)); //keep in mind that this is NOT entirely random! 
    int boxee = rand() % 5; 
    int i = 0; 
    while(i<5) 
    { 
    boxee = rand() % 5; 
    cout<<Box[boxee]<<endl; //this line might be wrong, my point is to print element of your array with boxee index 
    i++; 
    } 

} 
+0

感謝您的幫助! – mur7ay

1

Box[f] = Box[boxee];正在改變你正在挑選東西的「盒子」的內容。如果第一個隨機數是3,則項目3被複制到項目0,所以現在您有兩倍的機會在下一次通過循環時獲得該項目...

+0

謝謝你非常有幫助。 – mur7ay

1

您正在覆蓋數組的元素隨機選擇的項目。

Box[f] = Box[boxee]; 

對於例如:如果boxee=1f=0,將在索引0覆蓋元件具有1,而在索引1處同時元件是相同的離去相同項目的兩個副本。

使用:std:random_shuffle改爲。

+0

謝謝!您的評論有幫助。 – mur7ay