我试图编写一个程序,从包含五个不同水果或蔬菜的数组中随机选择三个条目,然后将随机选择的内容显示给用户。现在,我很难理解为什么输出是不一致的,因为有时候当我运行它时,我会得到这样的结果:
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();有人能帮我理解我为什么要得到这个输出吗?谢谢!
发布于 2015-10-28 02:06:34
不要这样做:)就像@John3136指出的那样,你在搞乱你的Box变量。
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++;
}
}发布于 2015-10-28 02:01:48
Box[f] = Box[boxee];正在更改您正在从中挑选的"Box“的内容。如果第一个随机数为3,则将第3项复制到项0,所以现在您有两倍的机会在下一次循环中获得该项.
发布于 2015-10-28 02:03:43
您正在用随机选择的项覆盖数组的元素。
Box[f] = Box[boxee];例如:如果boxee=1和f=0,它将在索引0处用1覆盖元素,而在同一时间,索引1处的元素是相同的,留下两个相同的项副本。
使用:std:随机播放代替。
https://stackoverflow.com/questions/33381619
复制相似问题