我正在嘗試編寫一個程序,該程序從包含五種不同水果或蔬菜的數組中隨機選擇三個項目,然後將隨機選擇的內容顯示給用戶。現在我無法理解爲什麼我的輸出是不相符的,因爲有時當我運行它,我會得到這樣的事情:使用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();
有人可以幫助我瞭解爲什麼我得到這個輸出?謝謝!
'函數srand(時間(0))'是不是真的隨機的,這是一個僞隨機生成器。另外考慮使用std :: random代替。 – Daffyd
爲輸入法添加代碼。 //將內容添加到框 Box [f] = Box [boxee];似乎很腥......你重寫同一個數組的內容。 – Nandu