gpt4 book ai didi

c++ - 使用 for 循环显示内容

转载 作者:行者123 更新时间:2023-11-30 02:35:42 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,从包含五种不同水果或蔬菜的数组中随机选择三个项目,然后将随机选择的内容显示给用户。现在我很难理解为什么我的输出不一致,因为有时当我运行它时我会得到这样的东西:

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();

有人能帮我理解为什么我会得到这个输出吗?谢谢!

最佳答案

不要像你那样做:)就像 @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++;
}

}

关于c++ - 使用 for 循环显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com